How to configure proguard for javascript interface?

前端 未结 3 897
深忆病人
深忆病人 2020-12-01 13:59

I have a implemented a Webview which takes use of JavascriptInterface. It\'s working fine when not obfuscating, but at once Proguard is active, it does not work. I\'ve looke

相关标签:
3条回答
  • 2020-12-01 14:36

    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>;
    }
    
    0 讨论(0)
  • 2020-12-01 14:47

    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() {
                ...
            }
    
        }
        ...
    }
    
    0 讨论(0)
  • 2020-12-01 14:51

    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

    0 讨论(0)
提交回复
热议问题