Parsing the interaction between WebView and JS in Android _android

Source: Internet
Author: User

1.android use WebView to invoke the JS code on the Web page.
Android can be achieved through webview and JS interaction, in the program calls JS code, just want to webview control of the support JS property set to True, and then through the Loadurl can be directly invoked, as follows:
Mwebview.getsettings (). Setjavascriptenabled (True);
Mwebview.loadurl ("Javascript:test ()");

2. How to invoke Java code in Android on a Web page
Calling Java code in a Web page requires adding javascriptinterface to the WebView control. As shown below:

Copy Code code as follows:

Mwebview.addjavascriptinterface (New Object () {
public void Clickonandroid () {
Mhandler.post (New Runnable () {
public void Run () {
Toast.maketext (test.this, "Test invoke Java", Toast.length_long). Show ();
}
});
}
}, "demo");

In a Web page, just like calling the JS method, the call can be
<div id= ' B ' ><a onclick= "window.demo.clickOnAndroid ()" >b.c</a></div>

3. Java code calls JS and passes the reference
First you need a JS function with parameters, such as function Test (str), and then simply pass in the arguments when you call JS, as follows:
Mwebview.loadurl ("Javascript:test (' AA ')");

Call Java functions in 4.Js and pass parameters
First of all, you need the function form with parameters, but note that the parameters here need final type, that is, can not be modified, if you need to modify the value, you may set the intermediate variables, and then modify. As shown below:

Copy Code code 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 invoke Java" + string.valueof (j), Toast.length_long). Show ();
}
});
}
}, "demo");

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

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.