Search code examples
pythonpyqt5qwebkit

QWebKit how running js on page from python


How can I inject JavaScript into a page via QWebKit?

import sys
from PyQt5.QtCore import *
from PyQt5.QtWebKitWidgets import *
from PyQt5.QtWidgets import QApplication

js = "alert('test');"

def function():
    app = QApplication(sys.argv)

    web = QWebView()
    web.load(QUrl("url"))

    # run js

    web.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    function()

The js code is a simple example, I don't know exactly what code will be run.


Solution

  • You have to run through the evaluateJavaScript() method of the mainFrame of the page associated with the view. It is advisable to run it after loading the page:

    import sys
    from PyQt5.QtCore import QUrl
    from PyQt5.QtWebKitWidgets import QWebView
    from PyQt5.QtWidgets import QApplication
    
    js = "alert('test');"
    
    
    def function():
        app = QApplication(sys.argv)
    
        web = QWebView()
        web.load(QUrl("https://stackoverflow.com"))
        # web.page().mainFrame().evaluateJavaScript(js)
    
        def on_load_finished(ok):
            if ok:
                web.page().mainFrame().evaluateJavaScript(js)
    
        web.loadFinished.connect(on_load_finished)
    
        web.show()
    
        sys.exit(app.exec_())
    
    
    if __name__ == "__main__":
        function()