我打算在服务器端使用PyQt控制嵌入的WebKit浏览器。
在WebKit内运行的HTML页面中,我有一些继承的Javascript应用程序逻辑。
我该如何从主机进程(Python,PyQt)与Javascript进行通信,以便:
我可以调用页面内的Javascript函数
Python方法暴露给Javascript,可以通过参数从Javascript调用
我打算在服务器端使用PyQt控制嵌入的WebKit浏览器。
在WebKit内运行的HTML页面中,我有一些继承的Javascript应用程序逻辑。
我该如何从主机进程(Python,PyQt)与Javascript进行通信,以便:
我可以调用页面内的Javascript函数
Python方法暴露给Javascript,可以通过参数从Javascript调用
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_()