Android WebView (4) Interaction with html, androidwebview
How does WebView interact with html?
In many cases, WebView needs to interact with html, or control page activities through Java code or trigger Java code through js. WebView provides this mechanism.
First, let's take a look at the html code for interaction:
<! DOCTYPE html>
Simple html code, three lines of text, one button. Document. body. innerHTML is used to obtain the content of the body node in html.
Then we load it into WebView and enable js:
WebView. loadUrl ("file: // android_asset/MyHtml.html"); webView. getSettings (). setJavaScriptEnabled (true); webView. setWebViewClient (new WebViewClient () {@ Overridepublic void onPageFinished (WebView view, String url) {Toast. makeText (WebViewActivity. this, "webpage Loading completed", 0 ). show (); view. loadUrl ("javascript: window. handler. show (document. body. innerHTML); "); super. onPageFinished (view, url );}});
In the preceding html, the button clicking event uses an excuse: window. handler. To use this excuse, we need to first define:
class Handler {public void show(String data) {new AlertDialog.Builder(WebViewActivity.this).setMessage(data).create().show();}}
The public void show (String data) function is provided by this excuse. The preceding html and Java code have been called. But how does WebView know this?
Is it an excuse to call it? The answer is as follows:
webView.addJavascriptInterface(new Handler(), "handler");
This statement is used to bind an interface.
The running result is as follows: