来自android_asset的“ Content-Security-Policy”,“ frame-ancestors *”

时间:2019-05-15 13:27:18

标签: android webview content-security-policy

我正在编写一个Android应用程序,该应用程序加载本地网页,然后将该页面发布到某个内部iframe中,该iframe会显示与该用户有关的数据。

由于以下原因,远程站点拒绝显示在我的android_asset/page.html上:

Refused to display 'https://example/foo/bar' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors *".

我的代码是:

    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebViewClient(webViewClient);
    mWebView.setWebChromeClient(webChromeClient);
    mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    // this should do the trick... but it does not
    Map<String, String> extra  = new HashMap<>();
    extra.put("Content-Security-Policy", "frame-ancestors *" );
    mWebView.loadUrl("file:///android_asset/page.html", extra);

顺便说一句:这样做不起作用,因为它不受支持:

 <head>
    <meta http-equiv="Content-Security-Policy" content="frame-ancestors *">
 </head>

1 个答案:

答案 0 :(得分:0)

解决方案很简单:

我从loadUrl()更改为loadDataWithBaseUrl(),代码:

    try {
        String thePage = readRawText(getAssets().open("page.html"));
        mWebView.loadDataWithBaseURL("https://my-epic-site/", thePage, "text/html", "utf-8", "about:blank");
    } catch (IOException e) {
        e.printStackTrace();
    }

public static String readRawText(InputStream inputStream) throws IOException {
    if (inputStream == null) {
        return null;
    }

    BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder fileContent = new StringBuilder();
    String currentLine = bufferedReader.readLine();
    while (currentLine != null) {
        fileContent.append(currentLine);
        fileContent.append("\n");
        currentLine = bufferedReader.readLine();
    }
    return fileContent.toString();
}

这使页面认为它源自同一域。