19

I am using Android WebView to load some web pages. I need insert a piece of Javascript code to all the pages before they loaded.

I am trying to inject them on WebViewClient onPageStart callback.

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient(){

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        loadUrl("javascript:var output='test string';");
        }
})

mWebView.loadUrl("xxx.html");

HTML code:

<html>
<script>document.write(output);</script>
</html>

I expected My Js code loaded before HTML. But sometimes the JS code loaded after HTML.

Is there any way could solve my issue?

3
  • tell us more about what your js-code does...
    – Leonidos
    Jan 4, 2013 at 22:50
  • 1
    Hi wayne_bai,Can you tell me the solution for the above problem.I also have the same issue.Can you help me to solve the problem.I did't get the perfect solution.I also need to inject the javascript before loading the html. Jan 9, 2015 at 11:16
  • Use window.loadPage=function(){}. In function, write javscript
    – Maulik
    Jan 25, 2017 at 8:49

8 Answers 8

8

I had the same problem and I solved it. I hide WebView before load and show after page loaded.

webView.getSettings().setJavaScriptEnabled(true);
b.webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return false;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            b.webView.evaluateJavascript("javascript:window.document.getElementsByTagName('body')[0].style.color='white';", null);
        }
        else
        {
            b.webView.loadUrl("javascript:window.document.getElementsByTagName('body')[0].style.color='white';");
        }
        b.webView.setVisibility(View.VISIBLE);
    }

});

b.webView.setVisibility(View.INVISIBLE);
b.webView.loadUrl(PreferenceHelper.EULA_URL);
3

What about loading your page via javascript ?

Create a blank html page in your assets, that include your script plus this little function (I'm using jquery for the sake of simplicity here, but you can use another framework or not framework at all).

window.loadPage = function (url) {
    $.get(url, function(page) {
        $('html').replace(page);
    });
};

Then, on your android app :

mWebView.loadUrl("javascript: loadPage('xxx.html')");

Note : I didn't notice xxx.html could be in your assets too and not in a web server somewhere, in that case the ajax query will fail for security reasons, but you can forget the ajax request, read you html page in String from your android app and pass it as an argument to a slightly modified javascript function.

2

I had to do the same as you, since, in my case, the loading of the web page depended on some variables that needed to be set from the app through JavaScript.

After trying all the different permutations for loading the javascript before the page loads, this is what finally worked for me:

webView.loadUrl(url)
webView.settings.javaScriptEnabled = true
webView.settings.javaScriptCanOpenWindowsAutomatically = true

val javascript = "alert('some javascript message');window.JAVASCRIPT_GLOBAL_VARIABLE=true;"

webView.webViewClient = object : WebViewClient() {
    override fun onLoadResource(view: WebView?, url: String?) {
         super.onLoadResource(view, url)
         webView.evaluateJavascript(javascript) {}
    }    
}

If you need your javascript injected variables or methods to be available when the web view loads - for example, to authenticate the user, I had to also add the following to the javascript code to make it work reliably, every single time you open the web view.

window.location.replace('$url'); \\ this is the same url you want to inject the javascript into

Using the addJavascriptInterface only works if you want/can append some prefix to your Javascript methods. In my case, this was not an option since the same code should work for iOS as well.

2

You can inject your javascript before page loading like this:

  val mimeType = "text/html"
  val encoding = "utf-8"
  val injection = "<script type='text/javascript'>
        //Your JavaScript code here

       //**This line is important**
        window.location.replace('ACTUAL_URL');</script>"
  webView.loadDataWithBaseURL('ANY_DUMMY_URL', injection, mimeType, encoding, null)

The ACTUAL_URL should be URL you actually want to load. DUMMY_URL can be any URL, better keep it same as ACTUAL_URL.

0

One way, maybe not the most simple, is to use an HttpClient to read the data from the web server yourself, and then modify it and set it into the webview using

webview.loadData(mydata, "text/html", null);
0

I would use a combination of Phonegap and an interface for JavaScript.

In the main .java file, in OnCreate(), include this:

super.appView.addJavascriptInterface(new Object()
        {
          public void setOutput()
          {
            // here the body of your method in Android
          }
        }, "myInterface");

And then, in the .js file, include this (you have to import Phonegap in the same file, obviously, to catch the onDeviceReady method):

function onDeviceReady() {
        myInterface.setOutput();
      }

This would trigger your method from JavaScript when the device is ready, during the first moment of the launch of the application.

-2

you can try to put your java script inside html page then use android java script function call might be helpful

-2

You can use
webView.addJavascriptInterface("test string", "output");
to inject the object you want, before the web page loaded.

1
  • 1
    Isn't this only for making Java objects accessible in Webview Javascript scope? Can you use this to inject a javascript file into every page as well?
    – Tom
    Dec 30, 2018 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.