Javascript 接口不适用于 android 4.2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13775320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript interface not working with android 4.2
提问by Ravi
I am facing a serious bug of android OS Jelly Bean 4.2, here in my program I am using JavaScript to get the height of webpage and it is perfectly working from android 2.2 to 4.1 but when I tried to use the same code in android 4.2 so the JavaScript interface not working.
我正面临 android OS Jelly Bean 4.2 的一个严重错误,在我的程序中,我使用 JavaScript 来获取网页的高度,它在 android 2.2 到 4.1 之间完美运行,但是当我尝试在 android 4.2 中使用相同的代码时JavaScript 接口不起作用。
How can I fix this issue?
我该如何解决这个问题?
采纳答案by Frank Nguyen
And, if you are using Proguard, remember to add this
而且,如果您使用 Proguard,请记住添加此
-keepclassmembers class * {
@android.webkit.JavascriptInterface <methods>;
}
-keepattributes JavascriptInterface
-keep public class com.mypackage.MyClass$MyJavaScriptInterface
-keep public class * implements com.mypackage.MyClass$MyJavaScriptInterface
-keepclassmembers class com.mypackage.MyClass$MyJavaScriptInterface {
<methods>;
}
If it's still not OK, add this
如果还是不行,添加这个
-keepattributes *Annotation*
Note: your MyJavaScriptInterface must be Public class
注意:你的 MyJavaScriptInterface 必须是 Public 类
回答by jlovison
From the Android 4.2 documentation:
来自 Android 4.2 文档:
Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available your web page code (the method must also be public). If you do not provide the annotation, then the method will not accessible by your web page when running on Android 4.2 or higher.
注意:如果您已将 targetSdkVersion 设置为 17 或更高,则必须将 @JavascriptInterface 注释添加到您希望在网页代码中可用的任何方法(该方法也必须是公共的)。如果您不提供注释,则在 Android 4.2 或更高版本上运行时,您的网页将无法访问该方法。
Source: Android WebView Doc
回答by Nicolas
According to the doc: Android docSince Android 4.2 you have to annotate your method with @JavascriptInterface (and your method has to be public).
根据文档:Android doc从 Android 4.2 开始,您必须使用 @JavascriptInterface 注释您的方法(并且您的方法必须是公开的)。
回答by Andreyul
Proguard config that works for me with target API 17+:
适用于目标 API 17+ 的 Proguard 配置:
-keep @interface android.webkit.JavascriptInterface
-keepclassmembers class * {
@android.webkit.JavascriptInterface <methods>;
}