16_android_webview interaction with JavaScript

Source: Internet
Author: User

Not only can you run HTML code in WebView, but more importantly, WebView can call each other with JavaScript. In other words, you can get WebView content in JavaScript, and in the meantime, you can call the JavaScript method in WebView.

The following example analyzes the interaction of WebView with JavaScript.

1. The first step is to declare WebView (activity_main.xml) in the layout file

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    tools:context= "${relativepackage}.${activityclass}" >    <webview        android:id= "@+id/webview1"        android:layout_width= "match_parent"        android:layout_height= "Match_parent"/></relativelayout>

2. Store HTML files under the assets directory of the project (user.html)

<! DOCTYPE html>

remark: in order for WebView to load the Assets,android SDK from the APK file, a schema is provided with the prefix "file:///android_asset/". WebView encountered such a schema, go to the current package in the assets directory to find content

3. Implementation of the specific code (see code comments for details)

public class Mainactivity extends Activity {//Declare control object private WebView webview;//declaration Handler Object Private Handler Handler = new H Andler (); @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);//Get Control object WebView = (WebView) Findviewbyid (R.ID.WEBVIEW1);// Gets the WebView control Property object WebSettings websettings = Webview.getsettings ();//support for JavaScript code websettings.setjavascriptenabled ( true);//Add JavaScript Interface object Webview.addjavascriptinterface (new Javascriptuser (), "csdn");// Webchromeclient is mainly used to assist WebView in the processing of JavaScript dialog boxes, website icons, site titles, and page loading progress. Webview.setwebchromeclient (New Webchromeclient () {//Processing confirmation Box @overridepublic Boolean onjsconfirm (webView view, String URL , String message, final Jsresult result) {//Create Builder object New Alertdialog.builder (Mainactivity.this). Settitle (" Onjsconfirm "). Setmessage (Message). Setpositivebutton (" Confirm ", new Onclicklistener () {@Overridepublic void OnClick ( Dialoginterface Dialog,int which) {result.cancel ();//If you do not cancel, the button can only be processed once, the cancellation is not limited}). Show (); return true;} Handle the Cue box @overridepublic boolean onjsprompt (WebView view, string URL, String message,string defaultvalue, final Jspromptresult result) {//Create Builder object New Alertdialog.builder (Mainactivity.this). Settitle ("Onjsprompt"). Setmessage (message). Setpositivebutton ("Confirm", new Onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog,int which) {Result.cancel ();}}). Show (); return true;} Handling Warning Box @overridepublic Boolean onjsalert (WebView view, string URL, string message,final jsresult result) {/* * Toast.maket Ext (mainactivity.this, message, 1). Show (); * * RESULT.CONFIRM (); After confirmation, you can handle multiple clicks, otherwise the button can only click once *///create Builder object new Alertdialog.builder (Mainactivity.this). Settitle ("Onjsalert"). Setmessage (Message). Setpositivebutton ("Confirm", new Onclicklistener () {@Overridepublic void OnClick (dialoginterface Dialog,int which) {Result.cancel ();}}). Show (); return true;}); /load the displayed page rules: Schema FILE:///ANDROID_ASSETWEBVIEW.LOADURL ("file:///android_asset/user.html");} Class Javascriptuser {//PowerRemark: After the ANDROID17 version must be implemented through @JavascriptInterface annotations, otherwise the bug (see Exception)//This method is called in the Web page: <a href= ' Javascript:csdn.call ("+ Jsonobjs[y].phone+ ") >" + jsonobjs[y].name + "</a> @JavascriptInterfacepublic void Call (final String phone) {// The action to be processed is to be processed in Hanlder handler.post (new Runnable () {@Overridepublic void Run () {//here to implement the call operation, you must add the call permission < Uses-permission android:name= "Android.permission.CALL_PHONE"/>startactivity (New Intent (Intent.action_call, Uri.parse ("Tel:" + phone));}); Load all data notes: After the Android 17 version must be implemented via @JavascriptInterface annotations,//otherwise "uncaught Typeerror:object [Object Object] has no met Hod ' UserList ',//source:file:///android_asset/user.html (31)//This method is called in the Web page onload= "javascript:csdn.userList ()" @ javascriptinterfacepublic void UserList () {Handler.post (new Runnable () {@Overridepublic void run () {try {// Create JSON object Jsonobject jsonobject = new Jsonobject () jsonobject.put ("id", 1); Jsonobject.put ("Name", "Chenhj"); Jsonobject.put ("Phone", "110");//Create JSON object jsonobject jsonObject2 = NEW Jsonobject (); Jsonobject2.put ("id", 2); Jsonobject2.put ("Name", "Wangsan"); Jsonobject2.put ("Phone", "112");// Create a JSON array jsonarray Jsonarray = new Jsonarray (); Jsonarray.put (Jsonobject); Jsonarray.put (jsonObject2);// Convert the JSON array to string jsonstr = Jsonarray.tostring ();//TODO auto-generated method stub// Call the show function Webview.loadurl in JavaScript in the Web page ("Javascript:show ('" + Jsonstr + "')");} catch (Jsonexception e) {e.printstacktrace ();}}});}}}

4. Operating Instructions:

4.1 When successfully deployed, the interface after startup is as follows (note: the onload= "javascript:csdn.userList ()" called in the Web page calls the Webview.loadurl in the Java Code (" Javascript:show (' "+ Jsonstr +" ') ");

4.2 When clicking on the user name, such as CHJ, will enter the dial-up interface, indicating that the call method in Java was successfully invoked

4.3 The following interface appears when you click the pop-Up Warning box button, indicating that the onjsalert that was overridden in the Webchromeclient subclass was successfully invoked

4.4 The following interface appears when you click the Confirm Box button, indicating that the onjsconfirm that was overridden in the Webchromeclient subclass was successfully invoked


4.5 The following interface appears when you click on the box button, indicating that the onjsprompt that was overridden in the Webchromeclient subclass was successfully invoked


16_android_webview interaction with JavaScript

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.