【问题标题】:JavaScriptInterface methods not recognizable (Android webview)JavaScriptInterface 方法无法识别(Android 网页视图)
【发布时间】:2017-01-24 12:20:26
【问题描述】:

我的 MainActivity 中有:

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

        JavaScriptInterface( Context c ) {
            mContext = c;
        }

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

我读到问题可能是proguard。 所以我更新了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

【问题讨论】:

    标签: javascript java android ajax webview


    【解决方案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*
    

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

    【讨论】:

    • 谢谢,@JavascriptInterface 注释部分帮助了 - 我现在可以在 chrome 调试器中看到该方法,但由于某种原因它没有在我的应用程序代码中被调用。(javascript 代码是很好,因为我在应用程序的 iOS 版本上使用了相同的 javascript 代码,并且它在那里完美运行..)
    • 更改了您的 proGuard.pro 文件
    • 我可以用public *; 替换&lt;methods&gt;; 对吗?虽然它仍然不起作用,我可以在 chrome 调试器中看到该方法,但它没有在我的应用程序中被调用
    • 接口名称以$开头
    • 也可以试试#-keepattributes JavascriptInterface
    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 2019-08-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多