我正在尝试加载测试网页(在我的服务器中)。页面是:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<iframe width="420" height="315" src="http://www.youtube.com/embed/XGSy3_Czz8k?autoplay=1"/>
</body>
</html>
但是 webView 没有加载页面。在 %40-50 之后甚至没有调用 onProgressChanged
此外,所有从 url 加载 js 脚本的站点都会出现此问题。包括youtube、fb等
WebConsole: XMLHttpRequest cannot load https://googleads.g.doubleclick.net/pagead/id. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.youtube.com' is therefore not allowed access.
这里是我的设置
FrameLayout contentFrame = (FrameLayout) findViewById(R.id.ContentFrame);
WebView mWebView = new WebView(this);
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
mWebView.loadUrl("http://ozgur.dk/browser.html");
contentFrame.removeAllViews();
contentFrame.addView(mWebView);
布局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/ContentFrame"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
最佳答案
您可以通过启用名为 setAllowUniversalAccessFromFileURLs 的 WebSetting 来解决此问题
这发生在 Javascript 层。
您可以在这里阅读:CORS
关于Android WebView "No ' Access-Control-Allow-Origin' header 出现在请求的资源上”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37984896/