Home >Web Front-end >HTML Tutorial >android WebView (4) Interacting with html_html/css_WEB-ITnose
How WebView interacts with html
Many times WebView needs to interact with html, either by controlling page activities through Java code, or by triggering Java code through js. WebView provides a mechanism.
First, let’s take a look at the html code we need to interact with:
<!DOCTYPE html><html> <head> <title>MyHtml.html</title> </head> <body> <br> <br>大家晚上好 <br> <br>大家晚上好 <br> <br>大家晚上好 <br> <input type="button" value="测试" onclick="javascript:window.handler.show(document.body.innerHTML);" /> </body></html>
webView.loadUrl("file:///android_asset/MyHtml.html"); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { Toast.makeText(WebViewActivity.this, "网页加载完成", 0).show(); view.loadUrl("javascript:window.handler.show(document.body.innerHTML);"); super.onPageFinished(view, url); } });
class Handler { public void show(String data) { new AlertDialog.Builder(WebViewActivity.this).setMessage(data).create().show(); } }
webView.addJavascriptInterface(new Handler(), "handler");
This sentence is used to bind the interface.
The running results are as follows: