I’m trying to add to a PyQt5 application a QtWebEngineView widget. This widget must load the following very simple SVG (which, by specs, I cannot modify):
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="100" r="50" fill="red" />
<script type="text/javascript"><![CDATA[
alert("tag")
mynamespace.myfunction();
]]></script>
</svg>
But obviously, I need to define mynamespace
beforehand, so I’m trying the following in my widget constructor:
class MyWebPageView(QtWebEngineView):
def __init__(svg,*args,**kwargs):
super().__init__(*args,**kwargs)
js_script = QWebEngineScript()
js_script.setSourceCode("""
alert("qwebenginescript");
const mynamespace = { myfunction: function() { alert("success");}};
""")
js_script.setInjectionPoint(QWebEngineScript.DocumentCreation)
self.page().scripts().insert(js_script)
time.sleep(3) #to be sure this is not a timing issue
self.load(QUrl("file:///path/to/svg.svg"))
I expect the QWebEngineScript
to be executed before the SVG’s <script>
code, but what I see is first the the “tag” alert, and only then the “qwebenginescript” alert. The red circle is properly drawn, but the “success” alert never shows, and I get the following error message:
js: Uncaught ReferenceError: mynamespace is not defined
How can I ensure the QWebEngineScript is really executed first?
(Note: this is a follow-up of this question: https://stackoverflow.com/posts/79059688)