Android WebView (4) Interaction with html, androidwebview

Source: Internet
Author: User

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:





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.