Differences in Android 4.2.1, WebView and javascript interfaces

I have a webview with an added javascript interface that works fine on most devices, except for those running Android 4.2.1.

I deleted most of the code and stayed with very simple code:

this.webView.getSettings().setJavaScriptEnabled(true); this.webView.setWebChromeClient(new WebChromeClient()); this.webView.addJavascriptInterface(new Object() { public void handshake() { Log.d("JS", "handshake no params"); } public void handshake(String json) { Log.d("JS", "handshake with params: " + json); } }, "Android"); 

In javascript, the side of the testing code looks like this:

 Android.handshake(); 

But I get this in logcat:

E / Web Console: Not Prepared TypeError: Object [object Object] does not have a "handshake" method

Again, this same exact thing works great on devices that have older Android os versions (<4.2.1) that I tested (minimum version 2.3.3).

The strange thing is that if I start a completely new project, having only one action, having only WebView, with the same code, everything works fine even for 4.2.1, but when it is part of my actual project, everything breaks. I am not doing anything with a webview that is not included in these code snippets that I provided.

What's the strangest thing for me is that javascript finds an Android object, but it just doesn't have the requested method (handshake), how can it be?

Any help would be greatly appreciated, as it made me go crazy for the past 2 weeks or so (this is a mistake that I return all the time and then give up, etc.). Thank.

+32
javascript android webview
Dec 25
source share
2 answers

From the Android 4.2 documentation:

Note: if you set targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method by which you want to get the code for your web page (this method should also be public). If you do not provide annotation, the method will not be available on your web page when running on Android 4.2 or higher.

+95
Jan 04 '13 at 10:15
source share

You must annotate (@JavascriptInterface) the methods in the Java class that you want to make available to JavaScript.

  public class JavaScriptInterface { Context context; JavaScriptInterface(Context c) { context = c; } @JavascriptInterface public void edit(String postid) { Log.d("myApp", "EDIT!"); //do stuff } } 

It worked for me. Try it.

+4
Apr 3 '15 at 12:16
source share



All Articles