Methods Called from a WebView Need the @JavascriptInterface Annotation — Android Development
Since Android 4.2, native methods called from JavaScript in a WebView must be annotated with @JavascriptInterface.
Android 4.2 Jelly Bean introduced some security enhancements that are important for developers. When you call a native Java method from a WebView, that method must now be annotated with @JavascriptInterface. This applies to all apps that target API level 17 or higher. The example below shows how to call a native method from a WebView.
// appview is a webview object.
mnc = new MyNativeClass( appView );
// Adds java script interface to native class
appView.addJavascriptInterface(mnc, "MyNativeClass");
// Native class
public class MyNativeClass {
private WebView mAppView;
public MyNativeClass(WebView view)
{
mAppView = view;
}
@JavascriptInterface
public String getMyName() {
return "tech.sarathdr.com";
}
}
You can call this native method from JavaScript as follows:
var name = window.MyNativeClass.getMyName();
You can read more in the Android Developers Blog post on security enhancements in Jelly Bean