简体   繁体   English

从 pyqt QWebEngineView 启动 javascript 函数

[英]Launch javascript function from pyqt QWebEngineView

I'm planning on executing a javascript function from pyqt QWebEngine.我打算从 pyqt QWebEngine 执行一个 javascript 函数。 I followed a example which was using a map and map bound were retrieved when a Qt application button was pushed, and wrote a small example.我遵循了一个使用地图的示例,并在按下 Qt 应用程序按钮时检索了地图绑定,并编写了一个小示例。

html: html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
</head>

<body>

<script>
    function helloWorld(param1, param2) {
        return "Hello world " + param1 + " " + param2;
    }
</script>

</body>
</html>

Python: Python:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.form_widget = FormWidget(self)
        _widget = QWidget()
        _layout = QVBoxLayout(_widget)
        _layout.addWidget(self.form_widget)
        self.setCentralWidget(_widget)


class FormWidget(QWidget):
    def __init__(self, parent):
        super(FormWidget, self).__init__(parent)
        self.__controls()
        self.__layout()
        self.browser.page().runJavaScript("helloWorld()", self.ready)

    def __controls(self):
        html = open('test.html', 'r').read()
        self.browser = QWebEngineView()
        self.browser.setHtml(html)

    def __layout(self):
        self.vbox = QVBoxLayout()
        self.hBox = QVBoxLayout()
        self.hBox.addWidget(self.browser)
        self.vbox.addLayout(self.hBox)
        self.setLayout(self.vbox)

    def ready(self, returnValue):
        print(returnValue)

def main():
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    app.exec_()


if __name__ == '__main__':
    sys.exit(main())

Nevertheless, I get the following error:不过,我收到以下错误:

js: Uncaught ReferenceError: helloWorld is not defined
None ----> This is the return value printed at ready()

What am I missing?我错过了什么?

You have 2 errors:你有2个错误:

  • You are calling the function when the page has not yet finished loading.当页面尚未完成加载时,您正在调用该函数。

  • Your function needs 2 parameters, although it also works but will signal undefined .您的函数需要 2 个参数,虽然它也可以工作,但会发出undefined信号。

Using the above you get the following:使用上述内容,您将获得以下内容:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.form_widget = FormWidget(self)
        _widget = QWidget()
        _layout = QVBoxLayout(_widget)
        _layout.addWidget(self.form_widget)
        self.setCentralWidget(_widget)


class FormWidget(QWidget):
    def __init__(self, parent):
        super(FormWidget, self).__init__(parent)
        self.__controls()
        self.__layout()

    def __controls(self):
        html = open('test.html', 'r').read()
        self.browser = QWebEngineView()
        self.browser.setHtml(html)
        self.browser.loadFinished.connect(self.onLoadFinished)

    def onLoadFinished(self, ok):
        if ok:
            self.browser.page().runJavaScript("helloWorld(1, \"2\")", self.ready)

    def __layout(self):
        self.vbox = QVBoxLayout()
        self.hBox = QVBoxLayout()
        self.hBox.addWidget(self.browser)
        self.vbox.addLayout(self.hBox)
        self.setLayout(self.vbox)

    def ready(self, returnValue):
        print(returnValue)

def main():
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    return app.exec_()


if __name__ == '__main__':
    sys.exit(main())

plus:加:

To visualize the output of the js console you must overwrite the javaScriptConsoleMessage method of QWebEnginePage :要可视化 js 控制台的输出,您必须覆盖QWebEnginePagejavaScriptConsoleMessage方法:

...
class WebEnginePage(QWebEnginePage):
    def javaScriptConsoleMessage(self, level, message, lineNumber, sourceID):
        print("javaScriptConsoleMessage: ", level, message, lineNumber, sourceID)


class FormWidget(QWidget):
    ...
    def __controls(self):
        ...
        self.browser = QWebEngineView()
        self.browser.setPage(WebEnginePage(self.browser))
        ...

To verify this you must use console.log(...) :要验证这一点,您必须使用console.log(...)

*.html *.html

...
<script>
    function helloWorld(param1, param2) {
        console.log("Hello world")
        return "Hello world " + param1 + " " + param2;
    }
</script>
...

Output:输出:

javaScriptConsoleMessage:  0 Hello world 12 data:text/html;charset=UTF-8,%3C%21DOCTYPE%20html%3E%0A%3Chtml%3E%0A%0A%3Chead%3E%0A%20%20%20%20%3Cmeta%20charset%3D%22UTF-8%22%3E%0A%3C%2Fhead%3E%0A%0A%3Cbody%3E%0A%0A%3Cscript%3E%0A%20%20%20%20function%20helloWorld%28param1%2C%20param2%29%20%7B%0A%20%20%20%20%09console.log%28%22Hello%20world%22%29%0A%20%20%20%20%20%20%20%20return%20%22Hello%20world%20%22%20%2B%20param1%20%2B%20%22%20%22%20%2B%20param2%3B%0A%20%20%20%20%7D%0A%3C%2Fscript%3E%0A%0A%3C%2Fbody%3E%0A%3C%2Fhtml%3E

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM