I am planning to use PyQt to control an embedded WebKit browser on the server side.
我计划使用PyQt来控制服务器端的嵌入式WebKit浏览器。
I have some inherit application logic in Javascript in the HTML page running inside WebKit.
在WebKit中运行的HTML页面中,我在Javascript中继承了一些应用程序逻辑。
How could I communicate from the host process (Python, PyQt) with Javascript, so that
如何用Javascript与宿主进程(Python、PyQt)进行通信?
-
I can call Javascript functions inside the page
我可以在页面中调用Javascript函数
-
Python methods are exposed to Javascript and can be called from the Javascript, with arguments
Python方法公开给Javascript,可以从Javascript调用,并带有参数
1 个解决方案
#1
26
The following source code should be helpful:
以下的源代码应该是有用的:
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_()
#1
26
The following source code should be helpful:
以下的源代码应该是有用的:
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_()