Introduction to the principle and implementation of using Android Jsbridge

Source: Internet
Author: User

Introduction to the principle and implementation of using Android Jsbridge

Jsbridge

In Android, Jsbridge is no longer something new, and the way the home is implemented is slightly different. Most people know that there is a loophole in webview, see WebView in the interface hidden trouble with the mobile phone hanging horse use, although the vulnerability has been fixed on Android 4.2, Even with @javascriptinterface instead of Addjavascriptinterface, but due to compatibility and security issues, Basically we will not use the Android system to provide us with the Addjavascriptinterface method or the @javascriptinterface annotation to achieve, so we can only find a way to seek safe, It is also possible to implement programs that are compatible with all versions of Android.


First we come to understand why to use Jsbridge, in the development, in order to pursue the efficiency of development and portability, some of the display of strong pages we will be inclined to use H5 to complete, functional page we will prefer to use native to complete, and once the use of H5, In order to get the native experience in H5 as much as possible, we native layer needs to expose some methods to the JS call, such as, play toast Reminders, bombs dialog, share and so on, and sometimes even put H5 network request native to complete, A good example of Jsbridge is that it provides developers with JSSDK, which exposes many native layers of methods, such as payment, positioning, etc.


So, how to achieve a compatible version of Android and have a certain security Jsbridge? We know that in WebView, if Java to invoke JS method, is very easy to do, using Webview.loadurl ("javascript:function ()") can, so, On the Jsbridge native layer calls the H5 layer of one-way communication, but H5 layer how to tune native layer, we need to find such a channel, carefully recalled, webview there is a method, called Setwebchromeclient, The Webchromeclient object can be set, and there are three methods in this object, namely, Onjsalert,onjsconfirm,onjsprompt, when JS calls the corresponding method of the Window object, That is, the Window.alert,window.confirm,window.prompt,webchromeclient object will be triggered by the corresponding three methods, we can not use this mechanism to do some of their own processing it? The answer is yes.


As for the JS of the three methods of the difference, you can see the Qkxue.net JavaScript message box (basic tutorial). In general, we are not using Onjsalert, why? Because the frequency of the alert used in JS is still very high, once we occupy this channel, the normal use of alert will be affected, and confirm and prompt use frequency relative to alert, then lower. So in the end is the choice of confirm or prompt, in fact, the use of confirm frequency is not low, such as you click a link to download a file, this time if you need to pop up a prompt to confirm, click on the confirmation will be downloaded, point cancellation will not be downloaded, similar to this scenario or a lot of, Therefore cannot occupy confirm. And prompt is not the same, in Android, almost will not use this method, is used, will also be customized, so we can use this method completely. The method is to pop up an input box and let you enter it, and then return the contents of the input box when the input is complete. Therefore, occupy prompt is perfect again.


In this step, we have found a channel for Jsbridge two-way communication, the next is how to implement the problem. The implementation of this article is just a simple demo, if you want to use in a production environment, you also need to do a layer of encapsulation.

For normal communication, the development of communication protocols is essential. Let's recall the components of the familiar HTTP request URL (App development ty300.com). Shape as Http://host:port/path?param=value, we refer to HTTP, the development of Jsbridge components, our jsbridge need to pass to native what information, native layer to complete the corresponding function, and return the results? Obviously we need to call a method of a class to complete a function, we need to pass the class name and the method name in the past, in addition, the method calls the required parameters, in order to communicate conveniently, the parameters required by the native method are defined as JSON objects, native We pass this JSON object in JS in the past, native layer to get this object and then parse. In order to distinguish it from the HTTP protocol, our Jsbridge uses the Jsbridge protocol, for the sake of simplicity, the question mark does not apply to the key-value pair, we directly follow our JSON string, so we have a shape like the following URI.

Jsbridge://classname:port/methodname?jsonobj

Some people will ask, this port for why, in fact, the JS layer call native layer method, native need to return the execution results to the JS layer, but you will feel through the Webchromeclient object Onjsprompt method to return the return value to JS is not good, In fact, if you do, then this process is synchronous, if the native to perform asynchronous operations, the return value how to return it? At this time the port has played its due role, when we call the native method in JS, register a callback in JS, and then cache the callback in the specified location, Then the native layer executes the corresponding method by Webview.loadurl call JS method, callback corresponding callback. So how does JS know which callback to call? So we need to pass a storage location of callback, then we need to native layer call JS method when the storage location is passed back to the JS,JS and then call the corresponding storage location callback, the callback. Thus, the complete protocol is defined as follows:

Jsbridge://classname:callbackaddress/methodname?jsonobj

Suppose we need to call the native layer of the logger class of the log method, of course, this class and method is bound to follow a certain specification, not all Java classes can be called, or the beginning of the article WebView loophole, the parameter is MSG, after the completion of the JS layer to have a callback, Then the address is as follows

Jsbridge://logger:callbackaddress/log? {"MSG": "Native Log"}

As for the address of this callback object, it can be stored in the Window object in JS. As for how to store, the text will slowly pour.

Above is the JS to native communication protocol, then on the other hand, native to JS communication protocol also needs to be developed, an essential element is the return value, this return value and JS parameter procedure, pass through the JSON object, the JSON object has a status code code, The message msg, as well as the return result, if code is not 0, an error occurred during execution, the error message in MSG, the result is null, and if execution succeeds, the returned JSON object is in result. Here are two examples, one successful call, and one call failure.

Manuscripts: Diligent Learning qkxue.net

Read the full version of the introduction of the use of Android Jsbridge principle and implementation

Introduction to the principle and implementation of using Android Jsbridge

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.