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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With