[PyQt] Qt WebChannel JavaScript API

Kovid Goyal kovid at kovidgoyal.net
Sun Aug 30 13:13:29 BST 2015


Here you go:

#!/usr/bin/env python3
# vim:fileencoding=utf-8

from PyQt5.Qt import *

qwebchannel_js = QFile(':/qtwebchannel/qwebchannel.js')
if not qwebchannel_js.open(QIODevice.ReadOnly):
    raise SystemExit(
        'Failed to load qwebchannel.js with error: %s' %
        qwebchannel_js.errorString())
qwebchannel_js = bytes(qwebchannel_js.readAll()).decode('utf-8')


def client_script():
    script = QWebEngineScript()
    script.setSourceCode(qwebchannel_js + '''
    new QWebChannel(qt.webChannelTransport, function(channel) {
        channel.objects.bridge.print('Hello world!');
    });
''')
    script.setName('xxx')
    script.setWorldId(QWebEngineScript.MainWorld)
    script.setInjectionPoint(QWebEngineScript.DocumentReady)
    script.setRunsOnSubFrames(True)
    return script


class WebPage(QWebEnginePage):

    def javaScriptConsoleMessage(self, level, msg, linenumber, source_id):
        try:
            print('%s:%s: %s' % (source_id, linenumber, msg))
        except OSError:
            pass

    @pyqtSlot(str)
    def print(self, text):
        print('From JS:', text)


app = QApplication([])
p = WebPage()
v = QWebEngineView()
v.setPage(p)
p.profile().scripts().insert(client_script())
c = QWebChannel(p)
p.setWebChannel(c)
c.registerObject('bridge', p)
v.setHtml('<p>Hello world!')
v.show()
app.exec_()


Run the above and in the console you will see 'From JS: Hello world!'
No need to use web sockets or other complications (Note that this
requires Qt 5.5). Similarly you can connect to signals emitted by the
PyQt object in javascript -- that is left as an exercise for the reader.

Kovid.

On Tue, Aug 25, 2015 at 08:38:21AM -0500, Dustin Falgout wrote:
> Hi,
> I'm hoping to use the Qt Webchannel Javascript API in an application I am working on. It is possible using PyQt5? The only documentation I can find online is the C implementation.[1] If anyone could point me in the right direction I'd really appreciate it. 
> [1] http://doc.qt.io/qt-5/qtwebchannel-javascript.html
> 
> Best Regards,
> -- Dustin FalgoutFreelance Web Developer
> E-mail: dustin at falgout.usGoogle/Skype: dustinfalgoutFreenode IRC: #antergos
> Web Development Services 		 	   		  

> _______________________________________________
> PyQt mailing list    PyQt at riverbankcomputing.com
> https://www.riverbankcomputing.com/mailman/listinfo/pyqt


-- 
_____________________________________

Dr. Kovid Goyal 
http://www.kovidgoyal.net
http://calibre-ebook.com
_____________________________________


More information about the PyQt mailing list