Three ways to interact with WebView JavaScript code and native code in Android

Source: Internet
Author: User
Tags call back

I. WebView vulnerability analysis in Android

Recently encountered a problem in the development process, that is, webview use, or need to solve the previous system (before 4.2) caused a vulnerability, although now the system version of the user is very few, but also can not ignore, about this loophole, here is not much to explain, perhaps some students have already understood, Originally wanted to write an article in detail, but the online knowledge too much, and are very detailed, did not get, here is roughly simple and clear to say a few words:

first, the cause of the vulnerability

The reason for this vulnerability is mainly due to the fact that the JS access to the local method in Android WebView is flawed, and we do know that the interaction in Android is a way of using WebView:

Addjavascriptinterface (New Jsobject (), "MYOBJ");

First parameter: Android native object; the second parameter is the object to be used in the JS code

So here is actually the equivalent of a mapping relationship, the local object in Android and JS objects can be associated.

So there is a problem here, before the 4.2 system, JS in the method by the object call without any annotation constraints, then it means that JS to get this object, you can call this object all the methods, and we know that the object in Android has a common method getclass () method, and this method can be obtained to the current class type class, And this type has a very important method is Class.forName, this method can load a class, here can load java.lang.Runtime This class, and this class can execute local command, then there will be a danger, such as here can execute command to get the local device SD card files and other information , very dangerous.

May be said above or some students do not understand, the following is a simple JS code to understand:


See this JS after the classmate should be good understanding, because we have the Android local through the WebView object mapping, then the WebView loading page if the JS code, then there will be this problem, here to go through all the objects in the window, Then find out if the object has a GetClass method, and some can invoke the runtime class with reflection to execute a specific command. In fact, this loophole is also effective in JS syntax features, here you can see the JS syntax is very flexible.


second, bug fixes

Of course, for Android4.2 after the system fixed the vulnerability, the repair method is also very simple, plus note constraints: @JavascriptInterface is only add this annotation method will be JS call, then we know that GetClass is in the object class, Certainly without this annotation, then the above JS code must not be executed. This solves the flaw.

Another problem is that the default Android system will add a JS mapping object to WebView: Searchboxjavabridge_ This object is the default after Android3.0, that is, through this object is also can be manipulated by the above code.


second, the WebView JS code and the local Code interaction mode

Said, this loophole, the following begins to say today's topic, why should first introduce this loophole? The reason is that if you want to solve this vulnerability in version 4.2, you need to take advantage of today's content, first to look at today's content is mainly about the android in WebView JS and local interaction of three ways:

The first way: adding object mappings through the Addjavascriptinterface method

This approach does not explain much, and is also the most commonly used in Android, but this way there is a risk is the above-mentioned vulnerability problem.


Here, a simple local object is defined, and the constraint annotation is added to the method that needs to be called. The JS code is also simple:


The advantage of this approach is that the use of simple and clear, local and JS conventions are also very simple, is the object name and method name contract is good, the disadvantage is that there is a vulnerability problem.



Second way: Use Webviewclient interface callback method to intercept URL

This approach is actually very simple to implement, that is, we can add the Webviewclient callback interface, intercept the URL in the Shouldoverrideurlloading callback method, and parse the protocol of this URL, If we find the agreement we agreed on, we begin to parse the parameters to execute the specific logic:


The code is also very simple, this method can intercept WebView loading URL process, get the corresponding URL, we can through this method, and the page JS convention good one protocol, look at the JS code:


After this JS code executes, it will trigger the local Shouldoverrideurlloading method, then parse the parameters and invoke the specified method.

This method is not the first method of the vulnerability problem, but the careful classmate can find that the convention between local and JS is a bit cumbersome, such as to agree on a good protocol, parameter names and other information, no first way convenient. And the main problem is that this can only be active call localization method, if you want the return value of the method, only through the WebView Loadurl method to execute the JS method, the return value is passed back: Mwebview.loadurl ("javascript: Clicktworesult ("+res+") ");


It is very tedious to see this way. It is also not advocated in Android.

Note: There is no first way in iOS like Android, and he is also for security reasons, so the interaction in iOS is the second way to do it, by blocking the URL, when it comes to the introduction of iOS this part of the content is described in detail.


The Third Way: intercept messages using the three methods of the Webchromeclient callback interface

The principle of this method is actually the same as the second approach, except that the blocking interface method is different:


Android WebView Add Webchromeclient interface, you can block JS in a few tips, that is, several styles of dialog box, in JS There are three commonly used dialog box method:

1. Alert is a pop-up warning box that adds \ n to the text to wrap.
2. Confirm Pop-up confirmation box, will return a Boolean value, through this value can be determined when clicking on the confirmation or cancellation. True indicates click on confirm, false means click Cancel.
3. Prompt popup input box, click Confirm to return the value in the Input box, click Cancel to return null.

So the three kinds of dialogs can be intercepted locally, then the third method is to intercept these methods, get their message content, and then parse it, for example, here we intercept the prompt method content:


Method parameter description for local interception:


Why intercept the prompt method, because this method can return the desired value, and for alert is unable to get the return value, confirm can only get two return values. Only the prompt method can return various types of values, which is the most convenient operation.

Then in this method and the second method of the same principle to parse the message content can be


iii. Results of implementation

Here is a direct look at the above three ways to perform the effect:

The first way:


The second way:


The Third Way:


Where the HTML code is as follows:



summary of four or three ways

All right, here we go. Three ways to WebView JS and local interactions in Android:

The first way: is the most common usage, convenient and simple, but there is a vulnerability problem in the 4.2 system

The second way: by intercepting the URL, the protocol calls the local method after parsing the contract, the disadvantage is that the constraint protocol is cumbersome, and return after the execution of the returned value is more troublesome. But there is no vulnerability issue, and this is the way iOS is used.

The Third Way: in fact, and the second way, but the method of interception has changed, here is the interception of JS Three dialog box method, and these three dialog box method is the difference between the return value problem, alert dialog method does not return a value, The Confirm dialog method has only two state return values, and the prompt dialog method can return any type of return value. The disadvantage is the same as the second method, the protocol contract is cumbersome, but there is no vulnerability problem.


v. About the WebView bug fixing strategy under 4.2

Finally, to introduce the issue of the vulnerability introduced in the article, although Google fixed the vulnerability after 4.2, but for the users before 4.2 How to deal with the vulnerability? The main thing here is to use the third way, to intercept the prompt method, the repair steps are simple:

1, we show ourselves a webview wrapper, rewrite his addjavascriptinterface method, and then internally maintain an object mapping relationship map


2. Construct a local JS code in the method of WebView loading page:


About the meaning of this JS code:

1> the Jsinterface in the above code is the name of the object to be registered, it registers two methods, OnButtonClick (arg0) and Onimageclick (arg0, Arg1, arg2), and if there is a return value, add the returned return.
2> prompt is our agreed string, which contains a specific identifier, MyApp:, followed by a string of JSON strings containing the method name, parameters, object names, and so on.
3> when JS calls OnButtonClick or Onimageclick, it will call back to the Java layer Onjsprompt method, we then parse out the method name, parameter, object name, and then reflect the call method.
4> Window.jsinterface This means that a JS object is declared on the window, declaring the method in the form: Method Name: Function (parameter 1, parameter 2)

And when is the time to load this JS code?

In the beginning when the WebView normal loading URL to load JS, but found that there is a problem, if the webview jump to the next page, the previously loaded JS may be invalid, so need to load again. This problem has been tried, need to load JS in the following several methods, they are webchromeclient and webviewclient method: Onloadresource,doupdatevisitedhistory, Onpagestarted,onpagefinished,onreceivedtitle,onprogresschanged


3, let JS call a JavaScript method, this method is called prompt method, through the prompt to the information in JS to pass through, this information should be we combine a meaningful text, may contain: specific identity, method name, parameters and so on. In the Onjsprompt method, we parse the passed text, get the method name, parameters, etc., and invoke the method of the Java object by invoking the specified method through the reflection mechanism.


4, about the return value, you can return back through the prompt, so that the results of the method in Java can be returned to JS.

With these steps, you can easily fix the vulnerability, but there are a few things to keep in mind:

1> need to filter out the object class method due to the form of reflection to get the method of the specified object, he will be the base class method will also be obtained, the topmost base class is object, so we do not inject GetClass method into JS, So we need to filter out the public method of object. Strictly speaking, there should be a list of methods to filter. Currently in my implementation, the methods that need to be filtered are:
"GetClass", "Hashcode", "Notify", "Notifyall", "equals", "toString", "Wait",

2> under Android 3.0, the system added a JS interface called Searchboxjavabridge_, to solve this security problem, we also need to remove this interface, call the Removejavascriptinterface method. This searchboxjavabridge_ seems to be related to Google's search box.

3> in the implementation process, we need to determine whether the system version is under 4.2, because more than 4.2, Android fixed this security issue. We just need to fix the system below 4.2.


Project case: http://download.csdn.net/detail/jiangwei0910410003/9641825


Vi. Summary

The role of WebView in Android is still very important, and now many applications are beginning to use the web version of the function, then in this process can not be avoided is the need for JS and local interaction, this article introduces in detail the current stage of the three ways of interaction, each of which has shortcomings and advantages, Of course, the best way is to use the system provides the first method described in this article, but need to fix Android4.2 the following vulnerabilities.


Click here for more information:

Focus on the public, the latest technology dry real-time push



Three ways to interact with WebView JavaScript code and native code in Android

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.