How to load a Javascript in WebView

Issue

I have loaded my Webpage in Android WebView using webview.loadUrl() and I am trying to inject a Javascript into the WebView using webview.evaluateJavascript().

But the problem here is, the Javascript is available in a remote location/url. I want to get the javascript from a remote location and inject it into WebView.

I have searched related to this question but all I have found is loading from string.

Solution

You can do it like this :

private static class WC extends WebViewClient {
    Handler handler1  null;
    WebView webView  null;
    byte[] b  null;

    public WC(Handler handler, WebView webView) {
        this.handler1  handler;
        this.webView  webView;
    }

    @Override
    public void onPageFinished(final WebView view, String url) {
        super.onPageFinished(view, url);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    injectScriptFromNetWork("http://192.168.216.254:4000/test.js");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void injectScriptFromNetWork(String urlStr) throws IOException {

        URL url  new URL(urlStr);
        HttpURLConnection urlConnection  (HttpURLConnection) url.openConnection();
        int code  urlConnection.getResponseCode();
        if (code  200) {
            InputStream inputStream  urlConnection.getInputStream();
            b  new byte[inputStream.available()];
            inputStream.read(b);
        }

        handler1.post(new Runnable() {
            @Override
            public void run() {
                String jsSource  Base64.encodeToString(b, Base64.NO_WRAP);
                webView.loadUrl("javascript:(function() {" +
                        "var parent  document.getElementsByTagName('head').item(0);" +
                        "var script  document.createElement('script');" +
                        "script.type  'text/javascript';" +
                        "script.innerHTML  window.atob('" + jsSource + "');" +
                        "parent.appendChild(script)" +
                        "})()");
            }
        });
    }
}

MainActivity.java code like this:

handler  new Handler(getMainLooper());
webView.setWebViewClient(new WC(handler, webView));
webView.loadUrl("file:///android_asset/index.html");

Forgave me, this is my first time answering questions on stackoverflow.

Answered By – 源贵董

Leave a Comment