Android Javascript注入错误拒绝执行内联脚本

时间:2016-05-25 10:18:48

标签: javascript android android-webview javascript-injection

我遇到以下问题:

每当我尝试从资源文件中注入JS(到外部站点)时,我都会收到以下错误

  

拒绝执行内联脚本,因为它违反了以下内容   内容安全政策指令:" script-src https:' unsafe-eval'"。   “不安全 - 内联”和“不安全”。关键字,哈希(' sha256 -...')或nonce   (' nonce -...')是启用内联执行所必需的。

我的代码是

private void injectScriptFile(WebView view, String scriptFile) {
    //inject function
    InputStream input;
    try {
        input = getAssets().open(scriptFile);
        byte[] buffer = new byte[input.available()];
        input.read(buffer);
        input.close();

        // String-ify the script byte-array using BASE64 encoding !!!
        String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);

        String loadFileJS = "" +
                "var parent = document.getElementsByTagName('head').item(0);" +
                "var script = document.createElement('script');" +
                "script.type = 'text/javascript';" +
                "script.async = true;"+
                // Tell the browser to BASE64-decode the string into your script !!!
                "script.innerHTML = window.atob('" + encoded + "');" +

                "parent.appendChild(script);" ;


        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            webview.evaluateJavascript(loadFileJS, null);
        } else {
            view.loadUrl("javascript:(function() {" +
                    loadFileJS +
                    "})()");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

这就是我调用注入函数的方法

injectScriptFile(webview, "Jquery/jquery.min.js");
injectScriptFile(webview, "scripts/functionalityJS.js");


此代码适用于某些网站(例如Facebook),而在其他网站(例如Dropbox)中,我收到上述错误消息。然而,错误是在特定版本的android(例如5.1)中,而在其他版本(例如4.2.2)中,它工作得很好。

任何帮助都会成为生命救星:)
谢谢!

0 个答案:

没有答案
相关问题