Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems when creating a script tag to a local file in android webview

I have an Android application that consist in a simple WebView that load a local html file in the assets folder of the project.

The HTML has a tag that calls (AJAX) an external service and expects as a response a String that represent a .js filename (say, 'test.js').

In test.js there is a simple funcion declaration, as:

var testFunction = function(){
    // some code here
}

The AJAX callback then construct via javascript a tag that points to the .js file and append it to the head of the document; then call the testFunction:

$.ajax('externalService').done(function(response){
    var script = // construct the script tag;
    $('head').append(script);
    testFunction();
}); 

Important: the script tag points to an external .js file, like

<script src="http://justatest.com/test.js">

... and all works fine!

Now i try to do the same thing putting the test.js inside the assets folder of the project. Obviously i changed the src of the script created in the callback with a relative path:

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

but when i try to invoke the function testFunction i get an error (testFunction is not defined).

The local path is correct (i put jquery.js in the same local folder of test.js and loaded it directly in the html with a with no errors).

I put all the attributes (like type="text/javascript") in the tag as well...

so, why the webview doesn't load a local .js file in this way?

thank you :)

EDIT: I tried the solution found in this thread:

jQuery getScript not working in Android WebView when using Local Assets/HTML/Resources

and it worked!!!!

like image 597
user1561017 Avatar asked Mar 26 '26 05:03

user1561017


1 Answers

I tried the solution found in this thread:

jQuery getScript not working in Android WebView when using Local Assets/HTML/Resources

and it worked!

I report the solution:

var scriptUrl = "test.js";
var head = document.getElementsByTagName("head")[0];
script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptUrl;
script.onload = function() { alert("Success"); };
script.onerror = function(e) { alert("failed: " + JSON.stringify(e)); };
head.appendChild(script);

So if i use the jquery append() method it doesn't work, but if i use the javascript appendChild method it work...

like image 173
user1561017 Avatar answered Mar 28 '26 19:03

user1561017



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!