Using Webviewjavascriptbridge to implement JS and Java interaction in Android (i)

Source: Internet
Author: User
Tags event listener tojson

This article originates from: http://blog.csdn.net/sk719887916/article/details/47189607, Skay Blog

According to the current situation of Android development, developers spend most of the time on the UI screen adaptation, the use of native control development costs are not so ideal, given that many projects and iOS based on a consistent UI interface, to the cost of Android UI development costs more expensive, So the current combination of HTML5 and native controls is a good choice to address UI adaptation, and the app performance will be combined with Java and native layers. No matter what kind of combination, in fact, the principle is similar, as long as it is in accordance with its Protocol, it is very easy, today we only for the HTML and Java layer combination, learning the next new Open source project-Webviewjavascriptbridge.

What is a Webviewjavascripbridge?

Webviewjavascriptbridge is a bridge between mobile UIView and HTML interactive communication, in the words of the author is the implementation of Java (iOS for OC) and JS of the mutual invocation of the bridge. Replaces the WebView's own Javascriptinterface interface, making our development more flexible and secure.


Second, why use Webviewjavascripbridge? For people who have been developing for Android for a while, Know Android 4.4 Before Google's WebView security loopholes, the site can be injected via JS can easily get the important information of the client, and even easy to invoke local code for rogue behavior, Google later found that the vulnerability, added defense measures, if JS call local code, developersmust beIn the code declarationJavascriptinterface,Column as before 4.0 we want to make WebView load JS just the following code:
Mwebview.addjavascriptinterface (New Jstojava (), "myjsfunction");  

     4.4 call need to join the join @JavascriptInterface note, if the code does not have this declaration, then it will not be able to make JS effective, that is to avoid malicious Web pages using JS to the Android client to steal and attack.

But even so, we often need to be in the JS record local code, to make some judgments and restrictions, or may also do some filtering and user-friendly hints, so javascriptinterface can not meet our needs, and hereby the Great God wrote Webviewjavascriptbridge frame.

Three how to use Webviewjavascripbridge 1 to introduce Jsbridge.jar into our project this jar, or jar source we can download on GitHub.
2 WebView package requires the use of the above package WebView
Use third-party view in layout, EG:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "Vertical" >    <!--button demo Java call Web--    <button         android:id= "@+id/button"        Android:layout_width= "Match_parent"        android:text= "@string/button_name"        android:layout_height= "48DP"        />        <!--webview Demo Web call Java--    <com.github.lzyzsd.jsbridge.bridgewebview        Android : id= "@+id/webview"        android:layout_width= "match_parent"        android:layout_height= "Match_parent" >     </com.github.lzyzsd.jsbridge.BridgeWebView></LinearLayout>
  3 Java code       
public class Mainactivity extends Activity implements Onclicklistener {private final String TAG = "mainactivity"; Bridgewebview WebView; Button Button;int result_code = 0;    Valuecallback<uri> Muploadmessage;    Static class Location {String address;        } static class User {String name;        Location location;    String Teststr; } @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (        R.layout.activity_main); WebView = (Bridgewebview) Findviewbyid (r.id.webview); button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (this); Webview.setdefaulthandler (new DefaultHandler ()); Webview.setwebchromeclient (new Webchromeclient () {@SuppressWarnings ("unused") public void Openfilechooser (Valuecallback<uri> uploadmsg, String Accepttype, String capture) {This.openfilechooser (uploadmsg);} @SuppressWarnings ("unused") public void Openfilechooser (valuecallback<uri> uploadmsg, String accepttype) {This.openfilechooser (uploadmsg);} public void Openfilechooser (valuecallback<uri> uploadmsg) {muploadmessage = Uploadmsg;pickfile ();}}); /load Local page//webview.loadurl ("file:///android_asset/demo.html");//Load Server Page webview.loadurl ("https://www.baidu.com") ;//must and JS the same name function, register the specific execution function, similar to the Java implementation class. Webview.registerhandler ("Submitfromweb", new Bridgehandler () {@Overridepublic void handler (String data, callbackfunction function) {String str = "This is the data that HTML returns to Java:" + data;//For example, you can process the raw data maketext (Mainactivity.this, str, Length_short). Show ();                LOG.I (TAG, "handler = submitfromweb, data from web =" + data); Function.oncallback (str + ", Java has been processed and intercepted part of:" + str.substring (0,5));});        /impersonate the user to get the local location user user = new user ();        Location location = new location ();        location.address = "Shanghai";        user.location = location;        User.Name = "Bruce"; Webview.callhandler ("Functioninjs", New Gson (). ToJson (user), new callbackfunction () {@Override Publ IC void OnCallBack (String data) {Maketext (mainactivity.this, "Web page is getting your location", Length_short). Show ();        }        }); Webview.send ("Hello");} public void Pickfile () {Intent chooserintent = new Intent (intent.action_get_content); Chooserintent.settype ("image/*") ; Startactivityforresult (Chooserintent, Result_code);}  @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent Intent) {if (Requestcode = = Result_code) {if (null = = Muploadmessage) {return;} Uri result = Intent = = NULL | | ResultCode! = RESULT_OK? Null:intent.getData (); Muploadmessage.onreceivevalue (result); muploadmessage = null;}} @Overridepublic void OnClick (View v) {if (Button.equals (v)) {Webview.callhandler ("Functioninjs", "Data from Ja VA ", new Callbackfunction () {@Overridepublic void OnCallback (String data) {//TODO auto-generated method stublog.i (TAG," R Eponse data from JS "+ Data";}});}}}

By instantiating WebView, the usage is not much different from the Android native view, setting the Webchromclient, setting the loaded HTML (same support for the network and local files), and then we need to give the Web registration and the HTML end of the specified JS method name. Code lists the Submitfromweband JS execution method name consistent, played the NDK JNI call friend also know must and C code between have a convention, actually JS Bridge and jni a bit similar,
By registering the handler to implement the callback, the Java code in the data returned by JS, after processing in the call Function.oncallback returned to JS. There's not much to explain here.
Must be the same as the JS function, register the specific execution function, similar to the Java implementation class. Webview.registerhandler ("Submitfromweb", new Bridgehandler () {@Overridepublic void handler (String data, callbackfunction function) {String str = "This is the data that HTML returns to Java:" + data;//For example, you can process the raw data maketext (Mainactivity.this, str, Length_short). Show (); LOG.I (TAG, "handler = submitfromweb, data from web =" + data);                Function.oncallback (str + ", Java has been processed and intercepted part of:" + str.substring (0,5));});

If WebView is just beginning to execute a piece of Java code, it can be implemented by Webview.callhandler (). Of course, we have to register the method and JS inside the method name consistent.
Webview.callhandler ("Functioninjs", New Gson (). ToJson (user), new callbackfunction () {            @Override public            Void OnCallback (String data) {Maketext (mainactivity.this, "Web page is getting your location", Length_short). Show ();            }        );

3 HTML and JS implement HTML code as follows,


JS Code
 <script> function Testdiv () {document.getElementById ("show"). InnerHTML = Document.getelementsbyt        AgName ("HTML") [0].innerhtml;            } function Testclick () {var str1 = document.getElementById ("Text1"). Value;            var str2 = document.getElementById ("Text2"). Value;            Send message to Java code var data = "Name=" + str1 + ", pass=" + str2; Window. Webviewjavascriptbridge.send (data, function (responsedata) {document.ge        Telementbyid ("Show"). InnerHTML = "Repsonsedata from java, data =" +responsedata});            } function TestClick1 () {var str1 = document.getElementById ("Text1"). Value;            var str2 = document.getElementById ("Text2"). Value; Call the local Java Method window. Webviewjavascriptbridge.callhandler (' Submitfromweb ', {' param ': str1}, Func     tion (responsedata) {               document.getElementById ("Show"). InnerHTML = "Send get ResponseData from Java, data =" + ResponseData        }            );        } function Bridgelog (logcontent) {document.getElementById ("show"). InnerHTML = Logcontent; }//registers the event listener function Connectwebviewjavascriptbridge (callback) {if (window. Webviewjavascriptbridge) {callback (Webviewjavascriptbridge)} else {Document.ad                        Deventlistener (' Webviewjavascriptbridgeready ', function () {            Callback (Webviewjavascriptbridge)}, False);  }}//registers a callback function, initializes the function Connectwebviewjavascriptbridge (bridge) {Bridge.init (function (message,                Responsecallback) {console.log (' JS got a message ', message);       var data = {' Javascript responds ': ' wee! '         };                Console.log (' JS responding with ', data);            Responsecallback (data);            }); Bridge.registerhandler ("Functioninjs", function (data, responsecallback) {document.getElementById ("show"). I                nnerhtml = ("data from Java: =" + data);                var responsedata = "Javascript Says right Back aka!";            Responsecallback (ResponseData);        }); }) </script>

This code is not difficult to understand, we registered a click event with the button named enter above, click to execute the following Testclick () method, and so on, the other button registration events are the same,


When you click the "Send Message to Native" button, JS sends a data to the Java layer (password and user name) via Webwiew's Jsbridage.send (), and then executes the Java layer callback function with function (). In this demo, the data returned by Java is inserted into the div of "show".

TestClick1 (): This method calls Callhandler to call the Java code submitfromweb function, can be combined with the above Activty code understanding, this function call we have been registered in the Java implementation of the good

Must be the same as the JS function, register the specific execution function, similar to the Java implementation class. Webview.registerhandler ("Submitfromweb", new Bridgehandler () {@Overridepublic void handler (String data, callbackfunction function) {String str = "This is the data that HTML returns to Java:" + data;//For example, you can process the raw data maketext (Mainactivity.this, str, Length_short). Show (); LOG.I (TAG, "handler = submitfromweb, data from web =" + data);                Function.oncallback (str + ", Java has been processed and intercepted part of:" + str.substring (0,5));});

Java Register JS function as above, then in JS Register method to register it,

In JS we can also register a callback function directly, register with Bridge.registerhandler (), and then call Responsecallback (ResponseData) to return the data to the Java code with the same name function. F

You can also call Init () directly to specify that the Web page first loads the above registered Java code.

  Connectwebviewjavascriptbridge (function (bridge) {            bridge.init (function (message, responsecallback) {                Console.log (' JS got a message ', message);                var data = {                    ' Javascript responds ': ' wee! '                };                Console.log (' JS responding with ', data);                Responsecallback (data);            });            Bridge.registerhandler ("Functioninjs", function (data, responsecallback) {                document.getElementById ("show"). InnerHTML = ("data from Java: =" + data);                var responsedata = "Javascript Says right Back aka!";                Responsecallback (ResponseData);            })        


Four summary through the above code example, it is not difficult to find this framework of elegance and simplicity, for both JS and Java, if the HTML JS need to call Java code, and Java code does not do any implementation, then this JS is not valid, and the Java Code Registration of the callback function, Not in the JS to achieve, then Java can not get JS remote data, so this, this communication is both sides, must be agreed by the two, so that the existence of the pre-existing JS injection to avoid the bug, but also a great increase in security, but also to ensure that our web data is not third-party app access, how to say, such as your project an HTML interface, by the Android browser or other third-party app malicious loading your website or Web page, then its Java code calls your JS function, such as by your JS pre-registration or implementation, or can not be called. This guarantees the uniqueness of this HTML, and third parties can load preview your Web page, but third-party Javanot with your JSInteractive communication.      As well as loading third-party pages, we can filter the third-party web pages to act as a friendly reminder to the user. The above code is only part of this open source framework function, there are a lot of features we need to dig, and then to dissect the internal implementation of this open source project. Welcome to read

Project Open Source Address: Https://github.com/lzyzsd/JsBridge

Copyright NOTICE: This article for Bo Master original article, please respect the original, reproduced please indicate the address.

Using Webviewjavascriptbridge to implement JS and Java interaction in Android (i)

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.