How can I embed a JavaScript file into a WebEngineView page?

I add a script tag to a webpage after being fully loaded in WebEngineView

, but it somehow doesn't work.

I am inserting a script by calling webview.runJavaScript

this code:

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

      

This is perfectly standard and works as expected to some extent, that is, if I go through the source of the html

page, the script tag is indeed added to the body.

The problem is that the script is not loaded, or is not evaluated, or whatever. All I know is in the example above, jQuery functions are not available. If I load a small JavaScript test file with one global variable, that variable is not available. Changing the url to http instead of qrc and pointing it to the web server doesn't matter.

Tag injection img

works fine; the image is loaded and displayed.

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

+3


source to share


1 answer


The problem stems from the asynchronous nature of QML and JavaScript.

I inserted a script tag for jQuery input and then I called a function to deconflict my inserted jQuery version from any jQuery version that might already be on the original page.

But I believe that webview did not finish parsing the built-in 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 it from the start.)



The solution was to insert a script tag with a bit of JavaScript which jQuery injects and then sets a timeout to wait 200ms before calling the deconflicting function. For example:

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()

      

This works reliably and is acceptable for my purpose.

+1


source







All Articles