Android WebView (iv) interacting with HTML

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.