Android JavascriptInterface Security?

后端 未结 6 1129
Happy的楠姐
Happy的楠姐 2020-12-08 05:19

From the documentation: http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface%28java.lang.Object,%20java.lang.String%29

\"Using a

6条回答
  •  臣服心动
    2020-12-08 06:03

    OverView

    To avoid the security issue of addJavaScriptInterface(), you need to design a communication protocol between native code and JavaScript.

    The following is a simple design of the communication protocol.

    In JavaScript

    To simplify the communication protocol, every function call that you want Android to handle should obey the following pattern

    /*
    classname string
    method name string
    params jsonObject
    */
    value=classname+":"+methodname+"?"+"params";
    window.promt(value,"");
    

    In Java

    One can override the onJsPrompt() in WebChromeClient.

    WebChromeClient.onJsPrompt(WebView view, String origin, String message, String defaultValue, final JsPromptResult result){
    //Parse className
    //Parse methodName 
    //Parse params
    //Create an instance of the target class by reflection. Call the target method with params.
    //Return true if all params in message valid, otherwise return false.
    }
    

    Cordova framework

    This is also how Cordova Plugin works. Although Cordova is more complicated, it adds callback function to "JS to Native Call", and allow native code call JavaScript

提交回复
热议问题