Parse the interaction between webview and js in Android

Source: Internet
Author: User

1. Use webview in android to call js Code on the webpage.
In Android, you can use webview to achieve interaction with js. To call js Code in a program, you only need to set the attributes of the webview control that support js to true ,, then, you can directly call it through loadUrl, as shown below:
MWebView. getSettings (). setJavaScriptEnabled (true );
MWebView. loadUrl ("javascript: test ()");

2. How to call java code in android on the webpage
To call java code on a webpage, you must add javascriptInterface to the webview control. As follows:

Copy codeThe Code is as follows: mWebView. addJavascriptInterface (new Object (){
Public void clickOnAndroid (){
MHandler. post (new Runnable (){
Public void run (){
Toast. makeText (Test. this, "Test calling java", Toast. LENGTH_LONG). show ();
}
});
}
}, "Demo ");

On a webpage, you only need to call the js method.
<Div id = 'B'> <a onclick = "window. demo. clickOnAndroid ()"> B. c </a> </div>

3. Java code calls js and transmits Parameters
First, the js function with parameters, such as function test (str), needs to be passed in when calling js, as shown below:
MWebView. loadUrl ("javascript: test ('aa ')");

4. Call java functions in Js and PASS Parameters
First, the function format with parameters must be the same, but note that the parameters here need the final type, that is, they cannot be modified later. If you need to modify the value, you can set the intermediate variable first, then modify. As follows:

Copy codeThe Code is as follows: mWebView. addJavascriptInterface (new Object (){
Public void clickOnAndroid (final int I ){
MHandler. post (new Runnable (){
Public void run (){
Int j = I;
J ++;
Toast. makeText (Test. this, "Test Call java" + String. valueOf (j), Toast. LENGTH_LONG). show ();
}
});
}
}, "Demo ");

Then, on the html page, use the following code <div id = 'B'> <a onclick = "window. demo. clickOnAndroid (2) "> B. c </a> </div>,
You can call

Related Article

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.