Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got a native Android app that contains a WebView. All my HTML, js & css has been added to the Android project in the assets folder so I'm initialising my WebView in the Java code like so...

WebView webView = (WebView)findViewById(R.id.webview);
webView.loadUrl("file:///android_asset/index.htm");

Everything works fine until I need to load an additional js file dynamically from JavaScript using the jQuery getScript method...

var scriptUrl = "scripts/dynamicScript.js";
$.getScript(scriptUrl , function() { alert("Success"); })
    .fail(function(e){ alert("failed: " + JSON.stringify(e)); });

Basically the script isn't loading and I get the following message:

failed: {"readState":4,"responseText":"", "status":404, "statusText":"error"}

I've also tried the following alternatives for scriptUrl and get exactly the same result and message:

"/scripts/dynamicScript.js"
"./scripts/dynamicScript.js"
"android_asset/scripts/dynamicScript.js"
"../android_asset/scripts/dynamicScript.js"
"file:///android_asset/scripts/dynamicScript.js"

I expect this might have something to do with the same-origin-policy. Any help getting this working is appreciated.

EDIT: In Addition

I've now also tried the following alternatives to $.getScript().

Using a non-async 'script' ajax call. This results in exactly the same as above...

$.ajax({
   url: scriptUrl, 
   dataType: 'script', 
   success: function() { alert("Success"); },
   error: function(e){ alert("failed: " + JSON.stringify(e)); },
   async: true
});

And also dynamically inserting a script tag into the head. This does not seem to work (for example if I simply have an alert in dynamicScript.js it is never seen)...

$("<script type='text/javascript' src='" + scriptUrl +"'></script>").appendTo("head");

I might also be worth pointing out that ALL of the above attempts work if I am hosting the website remotely instead of as local assets however this isn't a feasible solutiojn I.E it works if I instantiate as follows...

WebView webView = (WebView)findViewById(R.id.webview);
webView.loadUrl("http://remote-server/index.htm");
like image 473
Oliver Pearmain Avatar asked Mar 21 '12 12:03

Oliver Pearmain


1 Answers

Aha I seemed to have sussed it, this old classic gets the job done...

var scriptUrl = "scripts/dynamicScript.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);

Thanks to Phillip Fitzsimmons. Not sure why the jQuery script append didn't do the trick.

like image 51
Oliver Pearmain Avatar answered Nov 13 '22 18:11

Oliver Pearmain