How to configure proguard for javascript interface?

穿精又带淫゛_ 提交于 2019-11-27 08:51:49

Both your configurations could have worked if they hadn't contained typos:

  • ProGuard requires fully qualified names:

    NonObfuscateable -> com.project.NonObfuscateable

  • Compiled classes use '$' as a separator for inner classes:

    com.project.Activity_Webview.JavaScriptInterface -> com.project.Activity_Webview$JavaScriptInterface

In the console log, ProGuard prints out notes about such suspected typos.

A more general solution for keeping annotated Javascript interface methods:

-keepclassmembers class * {
    @android.webkit.JavascriptInterface <methods>;
}

In my case work only code:

proguard.cfg:

-dontwarn

-keepattributes Signature
-keepattributes SetJavaScriptEnabled
-keepattributes JavascriptInterface
-keepattributes InlinedApi
-keepattributes SourceFile,LineNumberTable
-keepattributes *Annotation*

-keepclassmembers class * {
    @android.webkit.JavascriptInterface <methods>;
}
-keepclassmembers class * {
    @android.webkit.JavascriptInterface <methods>;
}
-keepclassmembers class **.*$MyJavascriptInterface {
    *;
}
-keepclassmembers class **.*$JavaScriptInterface {
    *;
}

-keep public class **.*$MyJavascriptInteface
-keep public class **.*$JavaScriptInterface

Java code:

@SuppressLint("SetJavaScriptEnabled")
public class ActivityWebView extends Activity {
    ...
    webView.getSettings().setJavaScriptEnabled(true);
    webView.addJavascriptInterface(new MyJavascriptInterface(MyActivity.this), "MyJSI");

    ....

    public class MyJavaScriptInterface {

        Context context;

        MyJavascriptInterface(Context context) {
        this.context = context;
        }

        @JavascriptInterface
        @SuppressWarnings("unused")
        public void myjavascriptfunction() {
            ...
        }

    }
    ...
}
Heath Borders

If you're using obfuscation, in addition to Eric Lafortune's answer you also need:

-keepattributes JavascriptInterface

http://proguard.sourceforge.net/manual/usage.html#obfuscationoptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!