To facilitate interaction between webpages and Android applications, the Android system provides a mechanism for JavaScript webpage scripts in WebView to call Java methods. You only need to call the addJavascriptInterface method to map a Java object to a JavaScript Object.
1. Map a Java object to a JavaScript Object
01
<Strong> mWebView = (WebView) findViewById (R. id. wv_content );
02
MWebView. setVerticalScrollbarOverlay (true );
03
Final WebSettings settings = mWebView. getSettings ();
04
Settings. setsuppzoom zoom (true );
05
06
// WebView enables Javascript script execution
07
Settings. setJavaScriptEnabled (true );
08
Settings. setJavaScriptCanOpenWindowsAutomatically (true );
09
10
// Map the Java object to a Javascript Object named "js2java"
11
// In JavaScript, you can call the Java object method through "window. js2java ".
12
MWebView. addJavascriptInterface (new JSInvokeClass (), "js2java"); </strong>
View sourceprint?
1
/** Webpage Javascript call interface **/
2
Class JSInvokeClass {
3
Public void back (){
4
Activity. finish ();
5
}
6
}
2. Example of JavaScript calling Java objects
Call the back method of the preceding JSInvokeClass class object as follows:
1
Window. js2java. back ();
Author: Dean83