[pyinstaller] Cannot read properties of undefined (reading 'api')
Specification
- pywebview version: 5.3
- operating system: windows
- web renderer: default
Description
The js api works when I run it directly from source, but it doesn't work after compiling with pyinstaller.
example code:
import webview
from pathlib import Path
class Api:
def add(self,a,b):
return a+b
webview.create_window('Hello world', url= str(Path('web/index.html').absolute()),js_api=Api())
webview.start(http_server=True,debug=True)
web/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First App</title>
</head>
<body>
<h1>JS to Python</h1>
<main>
<button onclick="onClickOk()">OK</button>
</main>
<script>
async function onClickOk(){
let res = await window.pywebview.api.add(10, 15);
console.log(res);
}
</script>
</body>
</html>
I came to report the same thing. In PyInstaller, pywebview is unavailable, and window.pywebviewready event never happens. No lines in web console or terminal. Running directly as python main.py everything works.
Win 11, python 3.12.7.
pip freeze
altgraph==0.17.4
bottle==0.13.2
cffi==1.17.1
clr-loader==0.2.6
packaging==24.1
pefile==2023.2.7
proxy_tools==0.1.0
pycparser==2.22
pyinstaller==6.11.0
pyinstaller-hooks-contrib==2024.9
pythonnet==3.0.4
pywebview==5.3
pywin32-ctypes==0.2.3
setuptools==75.2.0
typing_extensions==4.12.2
However, @Liripo your code is incorrect. Before accessing window.pywebview you need to wait for event window.pywebviewready to happen, because pywebview may appear later.
When you run directly, it just happens to be fast enough to work as is.
I also have the same problem and would love to find a solution to it (tried to use Nuitka as an alternative, but it also didn't work, unfortunately). I noticed that linking other HTML files doesn't work as well.
Furthermore, I would be super grateful if someone found a solution to this issue and shared it here asap.
Due to thhe JS files refactor, pyinstaller hook needs to be updated. I pushed an updated hook to the master along with the pyproject.toml configuration, which should take care of this problem. I will release a hotfix version shortly.
Cool! And I chose that very day to start learning PyWebView and webdev in general.
Fixed in 5.3.1
I still hava this problem. version 5.3.2 I use nuitka + pywebview before,and it works well. but it doesnt work now.
5.3.1
maybe the fix on 5.3.1 makes some problem to nuitka?