1

I'm trying to add to a PyQt5 application a QtWebEngineView widget. This widget must load the following very simple SVG:

<!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("bar")
        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)
        
        self.page().runJavaScript(
            """
            alert("foo");
            const mynamespace = { myfunction: function() { alert("success");}};
            """)
        time.sleep(3) #to be sure this is not a timing issue
        self.load(QUrl("file:///path/to/svg.svg"))

I see the "foo" alert, then the "bar" 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

What have I done wrong?

5
  • When you load a new url the js namespace is cleared. You can just test it in a browser console: declare a variable, then open the svg from the address bar and the variable doesn't exist anymore. There may be solutions for this, but you should first clarify what you're actually trying to do. Commented Oct 6, 2024 at 18:47
  • Ha, of course... My issue is that I have to load SVGs that I'm not responsible for, and that are used initially in a context where some JS has already been loaded. I'm trying to emulate this JS loading, because by specs I cannot modify the SVGs themselves. Commented Oct 6, 2024 at 19:35
  • 2
    You need to employ user-script injection. See: QWebEngineScript. Commented Oct 6, 2024 at 20:11
  • I tried that, but even with InjectionPoint.DocumentCreation, the QWebEngineScript code is called after the JS embedded in the SVG, thus generating the same error message. Commented Oct 7, 2024 at 14:46
  • I wrote a new question regarding this QWebEngineScript issue: stackoverflow.com/questions/79064907 Commented Oct 8, 2024 at 8:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.