如何将JavaScript文件注入WebEngineView页面? [英] How can I inject JavaScript file into a WebEngineView page?

查看:494
本文介绍了如何将JavaScript文件注入WebEngineView页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网页完全加载到WebEngineView中后,我正在向网页中添加脚本标签,但是它以某种方式无声地失败了.

I'm adding a script tag to a web page once it's fully loaded in a WebEngineView, but it's silently failing somehow.

我通过使用以下代码调用webview.runJavaScript来注入脚本:

I inject the script by invoking webview.runJavaScript with this code:

var s = document.createElement('script');
s.src = "qrc:/jquery-2.1.4.min.js";
document.body.appendChild(s);

这是完全标准的,并且在一定程度上可以按预期工作,即,如果我查看页面的html源,则脚本标记确实已附加到正文中.

That's perfectly standard and to a certain extent it works as expected, i.e., if I view the html source of the page, the script tag has indeed been appended to the body.

问题在于该脚本未下载,未评估或其他原因.我只知道上面的示例中没有jQuery函数.如果我加载一个带有全局变量的小型JavaScript测试文件,则该变量也不可用.将URL更改为http而不是qrc并将其指向Web服务器没有什么区别.

The problem is that the script isn't being downloaded, or isn't being evaluated, or something. All I know is in the above example the jQuery functions aren't available. If I load a small JavaScript test file with one global variable, that variable's not available either. Changing the url to http instead of qrc and pointing it to a web server makes no difference.

注入img标签效果很好;图像被加载并显示.

Injecting an img tag works fine; the image is loaded and displayed.

但是JavaScript不知何故被破坏了.有人知道如何解决这个问题吗?

But JavaScript is broken somehow. Does anyone know how to fix this?

推荐答案

问题与QML和JavaScript的异步特性有关.

The problem had to do with the asynchronous nature of QML and JavaScript.

我正在插入一个脚本标签以注入jQuery,然后我调用了一个函数,以使插入的jQuery版本与原始页面中可能存在的jQuery版本冲突.

I was inserting a script tag to inject jQuery, and then I was calling a function to de-conflict my inserted version of jQuery from whatever version of jQuery might already be in the original page.

但是我相信在调用解冲突函数之前,webview尚未完成对插入的jQuery库的解析,因此失败了. (我对浏览器编程的经验不是很丰富,或者我可能从一开始就对此有所怀疑.)

But I believe the webview had not finished parsing the inserted jQuery library before my de-conflicting function was called, so it failed. (I'm not very experienced with browser programming or I might have suspected this from the beginning.)

解决方案是使用少量JavaScript插入脚本标签,该脚本标签插入jQuery,然后将超时设置为等待200ms,然后再调用de-conflict函数.像这样:

The solution was to insert a script tag with a small bit of JavaScript that inserts jQuery and then sets a timeout to wait 200ms before calling the de-conflict function. Like so:

function insertAuhJQuery(){
var s = document.createElement("script");
s.src = "qrc:/jquery-2.1.4.min.js";
document.body.appendChild(s);
window.setTimeout(deConflictJQuery, 200);
}

function deConflictJQuery(){
auh = {};
auh.$ = jQuery.noConflict(true);
}

insertAuhJQuery()

可以可靠地工作,并且对于我的目的是可以接受的.

That works reliably and is acceptable for my purpose.

这篇关于如何将JavaScript文件注入WebEngineView页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆