Issue
I am writing an Android-App, which loads a local webpage, and that page, posts to some inner iframe, which in reply will display data regarding that user.
The remote site refuses to display on my android_asset/page.html
because of:
Refused to display 'https://example/foo/bar' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors *".
My code is:
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);
BTW: Doing this, will not help as its not supported:
<head>
<meta http-equiv="Content-Security-Policy" content="frame-ancestors *">
</head>
Solution
Solution was simple:
I changed from loadUrl()
to loadDataWithBaseUrl()
, code:
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();
}
This makes the page, thinks it originated from the same domain.
Answered By - elcuco
Answer Checked By - Gilberto Lyons (JavaFixing Admin)