Loading jQuery from local assets in Android for a remote html page

android, android-webview, jquery, webview

Solution

Define a Javascript Interface like the one below that will read your jquery file from assets directory

class JavaScriptInterface {

    @JavascriptInterface
    public String getFileContents(){
        return readAssetsContent("jquery.js");
    }
}

Update WebView to enable JavaScript and to add JavaScriptInterface defined previously...

webView.getSettings().setJavaScriptEnabled(true);       
webView.addJavascriptInterface(new JavaScriptInterface(), "android");

Add javascript code snippet in your remote HTML to read the jquery file content through android JavaScript Interface...

<script type="text/javascript">
var s = document.createElement('script');
s.innerHTML = window.android.getFileContents();
document.head.appendChild(s);

//check if jquery is loaded now...
if(typeof $ != "undefined") {
    $(document).ready(function() {
        $('body').css('background','green');
    });
} else {
    document.body.innerText = "jQuery NOT loaded";
}
</script>

Problem

I'm trying to read a local javascript file (jQuery) stored in assets from an Android webview. I do not want to load-with-base-url since my images and html are served remotely. To Summarize : - Load local jQuery (in assets folder) into a remotely loaded page in Android webview. After long hours of browsing going in vain, I decided to put up this question here. Please help. Thanks!

Original source

Related problems