Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView Inject Javascript before html loaded

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?

like image 938
wayne_bai Avatar asked Dec 28 '12 04:12

wayne_bai


1 Answers

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);
like image 75
sagus_helgy Avatar answered Oct 19 '22 23:10

sagus_helgy