Thursday, March 21, 2013

JavascriptInterface not working with Android 4.2

As we all know android system allow you to call an android function directly from your web page by using the addJavascriptInterface(). Few fellow developers are facing issues for JavascriptInterface not working with Android 4.2. The obvious reason for this is because Google want to enhance security for Android platform.

The change will be very important for apps whose android:targetSdkVersion is set to 17 or higher, running on Android 4.2+ devices. Methods without the @JavascriptInterface annotation will not be accessible from JavaScript. Previously, any public method would be reachable via JavaScript. As Java classes usually have many inherited methods, public methods, including ones like getClass(). JavaScript could then use reflection to access other stuff, beyond what you had in mind. By limiting access to @JavascriptInterface methods, only those you specifically opt into being accessible will be usable from the JavaScript environment.

So from your JavascriptAdapterInterface class method call should be like this:-

 * Call method from webview to display toast.
@JavascriptInterface //required for sdk version 17 or higher
public void showToast(String message) {
     Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();