Before using JavaScript, you must first check whether Javascript is enabled or not in your application using "getJavaScriptEnabled ()" (defaults to FALSE). And the loadUrl () method is only used to load the current page. Its action is not related to JavaScript.
Example:
WebView Setup
// initialize webview
webView = (WebView) findViewById(R.id.webView); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true);
HTML loading in WebView
webView.loadUrl("file:///android_asset/testhtml.html");
Setting up WebChromeClient on webView
webView.setWebChromeClient(new MyJavaScriptChromeClient());
Class MyJavaScriptChromeClient Here we must override the onJsAlert () method to handle the JavaScript alert function.
private class MyJavaScriptChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message,final JsResult result) {
My html file is: testhtml.html:
<html> <body > <div onclick="alert('hello')"> Click Me !! </div> </body> </html>
How it works? When the text "Click Me !!" the android onJsAlert function is called on the WebView screen (WebView view, string URL, String message, final result of JsResult). The notification parameter is copied to the message parameter of the onJsAlert function. And the rest of the processing is done there. Here we show the AlertDialog.
Akilan
source share