Java webview:"无法从'Document'读取'cookie'属性:对此文档的访问被拒绝"

Sla*_*yes 11 java cookies 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
Run Code Online (Sandbox Code Playgroud)

但是当我想用Chrome Dev Tools调试我的webview时,我得到:

Uncaught SecurityError:无法从'Document'读取'cookie'属性:此文档拒绝访问.

我究竟做错了什么?

编辑:我忘了指定我在webview中显示一个离线页面HTML.

我不明白,当我在Chrome Developper Tools的控制台选项卡中时,我可以读取错误消息:SecurityError:无法从'Document'读取'cookie'属性:此文档的访问被拒绝.

如果我更改网址宽度"window.location =' http://www.google.fr ',页面会显示在我的网页视图上,如果我在选项卡控制台中输入'window.cookie'.我没有任何错误,我可以看到cookie值.

但是如果我使用'history.back()',webview会显示我的offlinepage,如果输入:'window.cookie',我总会得到同样的错误.

使用离线页面时显示错误消息.

可能是一个有点想法的sombody?

bit*_*ale 7

三年后...

但我有同样的问题。我只找到了一种解决方案。

只需在运行问题脚本(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")
Run Code Online (Sandbox Code Playgroud)

编辑

另一种解决方法:

如果你像上面的例子一样使用本地 HTML 或硬编码的 HTML,你需要使用这个方法加载 HTML:

webview.loadDataWithBaseURL("https://yoursite.com", YOUR_HTML, "text/html; charset=utf-8", "UTF-8", null)
Run Code Online (Sandbox Code Playgroud)

当您将本地 HTML 与 javascript 一起使用时,BaseURL 用于防止“未捕获的安全错误”,该 javascript 试图从 BaseURL 链接加载数据。