PyQt(PySide),WebKit和从/到Javascript的暴露方法

Mik*_*maa 11 javascript python webkit pyqt pyside

我打算使用PyQt来控制服务器端的嵌入式WebKit浏览器.

我在WebKit中运行的HTML页面中的Javascript中有一些继承应用程序逻辑.

我怎么能用Javascript从主机进程(Python,PyQt)进行通信呢

  • 我可以在页面内调用Javascript函数

  • Python方法暴露给Javascript,可以使用参数从Javascript调用

ped*_*ech 28

以下源代码应该是有用的:

import sys
from PyQt4.QtCore import QObject, pyqtSlot
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebView

html = """
<html>
<body>
    <h1>Hello!</h1><br>
    <h2><a href="#" onclick="printer.text('Message from QWebView')">QObject Test</a></h2>
    <h2><a href="#" onclick="alert('Javascript works!')">JS test</a></h2>
</body>
</html>
"""

class ConsolePrinter(QObject):
    def __init__(self, parent=None):
        super(ConsolePrinter, self).__init__(parent)

    @pyqtSlot(str)
    def text(self, message):
        print message

if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = QWebView()
    frame = view.page().mainFrame()
    printer = ConsolePrinter()
    view.setHtml(html)
    frame.addToJavaScriptWindowObject('printer', printer)
    frame.evaluateJavaScript("alert('Hello');")
    frame.evaluateJavaScript("printer.text('Goooooooooo!');")
    view.show()
    app.exec_()
Run Code Online (Sandbox Code Playgroud)