Android JavaScript cookie在Webview中不起作用

时间:2018-11-01 11:53:27

标签: javascript android cookies webview

我正在尝试使用WebView编写android应用。当我使用javascript从webView设置cookie时不起作用。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    WebView webView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    CookieManager.getInstance().setAcceptCookie(true);
    webSettings.setDomStorageEnabled(true);
    webView.loadUrl("file:///android_asset/index.html");
}

index.html代码:

<html>
    <head>
        <!--Meta-->
        <meta charset="utf-8">
    </head>
    <body>
        <script>
            document.cookie = "userName=Vasya";
            console.log("cookies:");
            console.log(document.cookie);
        </script>
    </body>
</html>

控制台输出:

11-01 17:35:16.239 26866-26866/? I/chromium: [INFO:CONSOLE(9)] "cookies:", source: file:///android_asset/index.html (9)
11-01 17:35:16.242 26866-26866/? I/chromium: [INFO:CONSOLE(10)] "", source: file:///android_asset/index.html (10)

1 个答案:

答案 0 :(得分:0)

我通过使用localStorage解决了这个问题 localStorage.setItem('foo', 'bar'); localStorage.getItem('foo')