JavaScriptInterface方法无法识别(Android webview)

时间:2017-01-24 12:20:27

标签: javascript java android ajax webview

我的MainActivity:

 webView.addJavascriptInterface( new JavaScriptInterface( this ), "ajaxHandler" );
....
 public class JavaScriptInterface
    {
        Context mContext;

        JavaScriptInterface( Context c ) {
            mContext = c;
        }

        public void DoSomething( String dataToPrint )
        {
          .....
        }
}

我读到这个问题可能是个问题。 所以我更新了proguard规则文件:

-keepclassmembers class fqcn.of.javascript.interface.for.webview {
     public *;
 }

-keep public class com.example.testapp.JavaScriptInterface
-keep public class * implements com.example.testapp.JavaScriptInterface
-keepclassmembers class * implements com.example.testapp.MainActivity.JavaScriptInterface{
    public *;
}

虽然在Chrome调试器中没有帮助,因为我在控制台中输入了ajaxHandler对象和DoSomething方法,我可以看到ajaxHandler对象为Object {}  但它是空的,方法DoSomething是undefined

1 个答案:

答案 0 :(得分:1)

接口类

public class JavaScriptInterface
    {
        Context mContext;

        JavaScriptInterface( Context c ) {
            mContext = c;
        }
        @JavascriptInterface //add this
        public void DoSomething( String dataToPrint )
        {
          .....
        }
}

在proGuard.pro文件中

-keep public class com.example.testapp.MainActivity$JavaScriptInterface
-keep public class * implements com.example.testapp.MainActivity$JavaScriptInterface
-keepclassmembers class * implements com.example.testapp.MainActivity$JavaScriptInterface{
     <methods>;
}
-keepattributes *Annotation*

使用$符号而不是.来获取内部接口类名称。