QWebView可以从Qt资源文件中加载*.js并运行它们吗?

Can QWebView load *.js from Qt resource files and run them?

本文关键字:运行 js 加载 Qt 资源 源文件 QWebView      更新时间:2023-10-16

我有qrc文件,看起来像这样:

 <qresource prefix="/web">
        <file alias="assets.js">../web/assets.js</file>
        <file alias="index.html">../web/index.html</file>
</qresource>

assets.js刚刚添加了allert弹出的功能:

    function myFunction() 
    {
        window.alert("Hello from assets.js");
    }

index.html中添加另一个javascript用于警报弹出,加载assets.js并添加2个按钮。第一个是从外部javascript文件(assets.js)调用窗口弹出,第二个调用嵌入到index.html文件中的javascript:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <script>
        function localFunction() 
        {
            window.alert('HTML loaded');
        }
    </script>
    <script src="assets.js"></script>
    <button onclick="myFunction()">External JS</button>
    <button onclick="localFunction()">Local JS</button>

  </body>
</html>

现在当我试图加载index.html在qtwebkit:

webView->load(QUrl(QStringLiteral("qrc:/web/index.html")));

我可以看到index.html已经加载好了(我可以看到两个按钮)当点击按钮,应该调用本地(html嵌入)javascript它的工作。点击第二个按钮没有任何作用。

似乎外部assets.js没有正确加载。有什么建议吗?

谢谢。

Javascript不会从html中求值。找不到你的JS文件。以下内容无效:

<script src="assets.js"></script>

显式地试试:

const QString js = readFile("qrc:/web/assets.js"); // Load your javascript file
view->page()->mainFrame()->evaluateJavaScript(js);

另一个更有效的解决方案:使用QRC系统并在sethhtml中设置baseUrl以正确链接所有文件:

   const QString html = readFile(":/index.html");
   view->setHtml(html, QUrl("qrc:/"));