我的 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
最佳答案
接口(interface)类
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*
使用 $
符号而不是 .
来获取内部接口(interface)类名。
关于无法识别的 JavaScriptInterface 方法(Android webview),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41828137/