Mukund
Mukund

Reputation: 1105

How to inject whole javascript function into webview and call it from android

What i have done:

I have a js file and an html file in my assets folder, i am loading that html file in webview.

then i manually edited the html file and added this code to it

<script src="file:///android_asset/myjs.js" type="text/javascript"></script>

and loaded the webview again and in the onPageFinished of webview I injected a javascript function call like this

webviewMine.loadUrl("javascript:changeColor('" + currentLine + "');");

This is working fine. Then i removed the script tag from the html page and tried to load the js in the assets by injecting that code in the onPageFinished like this

webviewTTS.loadUrl("javascript:<script src=\"file:///android_asset/js/makeBold.js\" type=\"text/javascript\"></script>");

but when the js call is executed from the android side it says the function changeColor does not exists in the html page, means my js injection of script tag is not working.

Is there any standard way of injecting js function like this?

If there is none please correct me.

Upvotes: 1

Views: 1261

Answers (1)

Vishnu Prasad
Vishnu Prasad

Reputation: 566

Use the below mentioned method to inject a js file from asset folder

public void injectScriptFile(WebView view, String scriptFile) {
    InputStream input;
    try {
        input = getAssets().open(scriptFile);
        byte[] buffer = new byte[input.available()];
        input.read(buffer);
        input.close();

        // String-ify the script byte-array using BASE64 encoding !!!
        String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
        view.loadUrl("javascript:(function() {" +
                "var parent = document.getElementsByTagName('head').item(0);" +
                "var script = document.createElement('script');" +
                "script.type = 'text/javascript';" +
                // Tell the browser to BASE64-decode the string into your script !!!
                "script.innerHTML = window.atob('" + encoded + "');" +
                "parent.appendChild(script)" +
                "})()");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Upvotes: 1

Related Questions