android WebView (4) Interacting with html_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:46:34
Original
1271 people have browsed it


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>
Copy after login


Simple html code, three lines of text, and one button. document.body.innerHTML is to get the content in the body node in html.
Then we load it in and enable js:
	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);		}	});
Copy after login

The click event of the button in the above html 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();		}	}
Copy after login

The function public void show(String data) is provided by this excuse, and has been called by the above html and Java code. But how does WebView know that there is such an excuse to call
? The answer is as follows:
webView.addJavascriptInterface(new Handler(), "handler");
Copy after login

This sentence is used to bind the interface.


The running results are as follows:





source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!