python - 无法使用 QWebEnginePage::runJavaScript() 更改背景图像

标签 python pyqt pyqt5 qtwebengine qwebengineview

我本来想解决this problem ,但正如我测试了 QWebEnginePage::runJavaScript() 的行为,我发现我什至无法使用 QWebEnginePage::runJavaScript() 和以下代码更改背景图像,那为什么呢?

import sys

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWebEngineCore import *


class WebEngineView(QWebEngineView):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.webPage = self.page()
        # self.webPage = WebEnginePage()
        self.webPage.load(QUrl('https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style'))
        self.webPage.runJavaScript('''
                                window.addEventListener("load", function(event) {
                                        alert(document.title);
                                        document.body.style.backgroundImage = "url('https://www.w3schools.com/jsref/img_tree.png')";

                                });
                     ''')  # QWebEngineScript.MainWorld


if __name__ == "__main__":

    app = QApplication(sys.argv)
    app.setAttribute(Qt.AA_UseSoftwareOpenGL)
    webEngineView = WebEngineView()
    webEngineView.show()
    sys.exit(app.exec_())

最佳答案

您想要修改 DOM,因此必须已经创建它,在您的情况下,您在加载页面之前使用 runJavaScript 并且未构建 DOM。考虑到有两种可能的解决方案:

import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets


class WebEngineView(QtWebEngineWidgets.QWebEngineView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.loadFinished.connect(self.on_load_finished)

        self.load(
            QtCore.QUrl(
                "https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style"
            )
        )

    @QtCore.pyqtSlot(bool)
    def on_load_finished(self, ok):
        if ok:
            script = """
            alert(document.title);
            document.body.style.backgroundImage = "url('https://www.w3schools.com/jsref/img_tree.png')";
            """
            self.page().runJavaScript(script)


if __name__ == "__main__":
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_UseSoftwareOpenGL)
    app = QtWidgets.QApplication(sys.argv)
    w = WebEngineView()
    w.show()
    sys.exit(app.exec_())
import sys

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets


class WebEngineView(QtWebEngineWidgets.QWebEngineView):
    def __init__(self, parent=None):
        super().__init__(parent)

        script = QtWebEngineWidgets.QWebEngineScript()
        name = "test"
        source = """
        alert(document.title);
        document.body.style.backgroundImage = "url('https://www.w3schools.com/jsref/img_tree.png')";
        """
        script.setName(name)
        script.setSourceCode(source)
        script.setInjectionPoint(
            QtWebEngineWidgets.QWebEngineScript.DocumentReady
        )
        script.setRunsOnSubFrames(True)
        script.setWorldId(QtWebEngineWidgets.QWebEngineScript.ApplicationWorld)
        self.page().scripts().insert(script)

        self.load(
            QtCore.QUrl(
                "https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style"
            )
        )


if __name__ == "__main__":
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_UseSoftwareOpenGL)
    app = QtWidgets.QApplication(sys.argv)
    w = WebEngineView()
    w.show()
    sys.exit(app.exec_())

关于python - 无法使用 QWebEnginePage::runJavaScript() 更改背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643674/

相关文章:

python - 如何安装 tensorflow_text?

python - 如何测试 PyQt/PySide 信号?

python - 如何阻止 QSvgWidget 生成它自己的窗口

Python PyQt5 QTreeWidget 子项

python - 带有 QML 和 PyQt 的项目列表

Python:从几何分布生成

python - 如何在 Django 中获取阿拉伯字符串的 Unicode 表示?

python - 仅在实际发生错误的情况下,如何仅将python错误(stderr)保存到日志文件?

qt - 如何实现基于树的 QComboBox

python - QTableWidget 的双击右键监听器