我试图在我的 WebView 中使用 cookie 但没有成功。
在我的代码中:
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptFileSchemeCookies(true);
cookieManager.setAcceptCookie(true);
cookieManager.acceptCookie();
myWebView = (WebView) getView(champHTML);// description du champ HTML WM16
myWebView.setBackgroundColor(Color.parseColor("#42A334"));
myWebView.getSettings().setJavaScriptEnabled(true); //autorisation javascript
但是当我想使用 Chrome 开发工具调试我的 webview 时,我得到:
Uncaught SecurityError: Failed to read the 'cookie' property from 'Document': Access is denied for this document.
我做错了什么?
编辑: 我忘记指定我在我的 WebView 中显示一个离线页面 HTML。
而且我不明白,当我在 Chrome 开发者工具的控制台选项卡中时,我可以阅读错误消息: SecurityError:无法从“文档”读取“cookie”属性:拒绝访问此文档。
如果我更改 url 宽度“window.location = 'http://www.google.fr',该页面将显示在我的 webview 上,如果我在选项卡控制台中键入“window.cookie”。我没有任何错误,我可以查看 cookie 值。
但是如果我使用“history.back()”,webview 会显示我的离线页面,如果输入:“window.cookie”,我总是得到同样的错误。
当我使用离线页面时显示错误消息。
可能有人有想法吗?
最佳答案
三年后...
但是我也遇到了同样的问题。而且我只找到了一个解决方案。
在运行问题脚本(Kotlin 代码)之前禁用 cookie:
companion object {
const val SOME_HTML = """
<!DOCTYPE html>
<html>
<head>
<script>
if(!document.__defineGetter__) {
Object.defineProperty(document, 'cookie', {
get: function(){return ''},
set: function(){return true},
});
} else {
document.__defineGetter__("cookie", function() { return '';} );
document.__defineSetter__("cookie", function() {} );
}
// Your problem script here
</script>
</head>
</html>"""
}
//And
webView.settings.javaScriptEnabled = true
webView.loadData(CHARTA_HTML, "text/html; charset=utf-8", "UTF-8")
编辑
另一种解决方法:
如果您像上面的示例一样使用本地 HTML 或硬编码 HTML,则需要使用此方法加载 HTML:
webview.loadDataWithBaseURL("https://yoursite.com", YOUR_HTML, "text/html; charset=utf-8", "UTF-8", null)
当您将本地 HTML 与尝试从 BaseURL 链接加载数据的 javascript 一起使用时,BaseURL 用于防止出现“Uncaught SecurityError”。
关于Java WebView : "Failed to read the ' cookie' property from 'Document' : Access is denied for this document",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28371812/