I have a html file that looks like this
<html>
<head>
This is a test
<script>
function testingConsole() {
console.log("Reached end of Body");
}
</script>
</head>
<body>
<script type="text/javascript">testingConsole();</script>
</body>
</html>
And my code looks like this
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chart);
webView = (WebView) findViewById(R.id.wvChart);
webView.loadUrl("file:///android_asset/Chart/chart.html");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("javascript:testingConsole();");
}
The html file is loading fine and the text “This is a test” is displayed in my WebView. And the script testingConsole(); is execuded by itself as it should be since html file is calling it. But when I call it from my code I get an error “Uncaught ReferenceError: testingConsole is not defined at null:1”
The
loadUrl(String)method does not execute synchronously; theWebViewdoes work on other threads to load the page and parse and execute any JavaScript in it.You should create an implementation/subclass of
WebViewClientthat overridesonPageFinished(WebView, String)and listen for the webview to complete the load of “chart.html”. Then you can call the secondloadUrlwith your JavaScript in it, and I bet it will work. I haven’t tested this, so let me know if it does.