How to load a Javascript in WebView


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.


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;

    public void onPageFinished(final WebView view, String url) {
        super.onPageFinished(view, url);
        new Thread(new Runnable() {
            public void run() {
                try {
                } catch (IOException e) {


    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()];
        } Runnable() {
            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)" +
} code like this:

handler  new Handler(getMainLooper());
webView.setWebViewClient(new WC(handler, webView));

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

Answered By – 源贵董

Leave a Comment