"Content-Security-Policy"、"frame-ancestors *" 来自 android_asset

"Content-Security-Policy", "frame-ancestors *" from android_asset

我正在编写一个 Android-App,它加载本地网页,然后该页面发布到某个内部 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>

解决方法很简单:

我从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();
}

这使得页面,认为它来自同一个域。