I used to do it by attaching an object
self.page().mainFrame().addToJavaScriptWindowObject("js_interface", self.jsi)
In 5.7 I do:
self.page().setWebChannel(self.jsi)
But I understandibly get a JavaScript error when I try to access exposed functions:
js: Uncaught ReferenceError: js_interface is not defined
Googling around I found that I should use qwebchannel.js, but I couldn't find the file or instructions on how to use it anywhere (there was some info, but only in some examples provided when installing QT, not PyQT).
You can include qwebchannel.js into html page using the script tag:
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
Then, create a web channel on the python side:
from PyQt5.QtCore import QObject, pyqtSlot
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView
class CallHandler(QObject):
@pyqtSlot()
def test(self):
print('call received')
view = QWebEngineView()
channel = QWebChannel()
handler = CallHandler()
channel.registerObject('handler', handler)
view.page().setWebChannel(channel)
JS code that interacts with the web channel:
new QWebChannel(qt.webChannelTransport, function (channel) {
window.handler = channel.objects.handler;
window.handler.test();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With