Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

android - How to configure proguard for javascript interface?

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 looked here at other answers, but i still can't get it working.

Some of the WebView class:

public class Activity_Webview {
private WebView webView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface (), "HTMLOUT");
        webView.setWebViewClient(mWebViewClient);
    }

    public class JavaScriptInterface implements NonObfuscateable{
        @JavascriptInterface
        public void processHTML(String html) {
        handleFinishFromWebView(html);
    }
}

What i've tried in Proguard:

-keep public class * implements com.project.NonObfuscateable
-keepclassmembers class * implements NonObfuscateable {
    public void processHTML(java.lang.String);
}

I've also tried this (when not implementing NonObfuscateable interface:

-keep public class com.project.Activity_Webview.JavaScriptInterface
-keep public class * implements com.project.Activity_Webview.JavaScriptInterface
-keepclassmembers class * implements com.project.Activity_Webview.JavaScriptInterface {
    <fields>;
    <methods>;
}

Does anybody have an idea of what could be wrong? Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...