WebView How to interact with HTML
Many times webview need to interact with HTML, either through Java code to control the page activity, or through JS trigger Java code, WebView provides the medium mechanism.
First, let's look at the HTML code we need to interact with:
<! DOCTYPE html>
Simple HTML code, three lines of text, a button. Document.body.innerHTML is to get the contents of the body node in the HTML.
Then we load it in and turn on 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, "Web page loading complete", 0). Show (); View.loadurl ("Javascript:window.handler.show ( Document.body.innerHTML); "); super.onpagefinished (view, URL);});
In the above HTML the button's Click event uses an excuse: Window.handler. To use this excuse we need to define it first:
Class Handler {public void Show (String data) {new Alertdialog.builder (webviewactivity.this). Setmessage (data). Create () . Show ();}}
The function public void Show (String data) is provided by this excuse, and the above HTML and Java code have been called. But how can webview know that there is this
An excuse to call it? The answers are as follows:
Webview.addjavascriptinterface (New Handler (), "Handler");
This sentence is used to bind the interface.
The results of the operation are as follows:
Android WebView (iv) interacting with HTML