Android webview usage Summary 2 interaction between Java and JavaScript

Source: Internet
Author: User

Two methods are provided first.

Method 1:

// Load the HTML file first, and then call the JavaScript function in the HTML file

Webview. loadurl ("file: // android_asset/show.html ");

Webview. loadurl ("javascript: pushnewsdata ('" + strhtml + "')");

Method 2:

// Add the Javascript interface to the Java code, and then call the object in Java in the HTML file

Webview. addjavascriptinterface (strhtml, "mycontent ");

Let the browser support JavaScript first

Webview. getsettings (). setjavascriptenabled (true); // you can use the JS function to enable it.

The JS Code can be stored in the asset folder or on the server side. To change the content, you only need to change the server side.

<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> 

Java code

Corresponding call_java () method

webView.addJavascriptInterface(new Object(){public void showToastFromWeb(String msg){showToast(msg);}}, "interface_test");

Corresponding to alert and other methods

Webview. setwebchromeclient (New webchromeclient () {@ overridepublic void onprogresschanged (webview view, int newprogress) {// previously mentioned in the previous blog} @ overridepublic Boolean onjsalert (webview view, string URL, string message, jsresult result) {// todo auto-generated method stubreturn super. onjsalert (view, URL, message, result) ;}@ overridepublic Boolean onjsconfirm (webview view, string URL, string message, jsresult result) {// todo auto-generated method stubreturn super. onjsconfirm (view, URL, message, result) ;}@ overridepublic Boolean onjsprompt (webview view, string URL, string message, string defaultvalue, jspromptresult result) {// todo auto-generated method stubreturn super. onjsprompt (view, URL, message, defaultvalue, result );}});

Load HTML

//webView.loadUrl("javascript:btn_test()");webView.loadUrl("file:///android_asset/test.html");


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.