Cookie未存储在Android Webview

时间:2017-06-02 08:34:43

标签: javascript java android cookies webview

我有一个纯HTML + CSS + JS应用程序,我正在尝试使用Webview嵌入到Android应用程序中。该应用程序一切正常,但不存储cookie。我已经尝试过这些质量保证中的建议,但它们似乎都不起作用:

Make Android WebView not store cookies or passwords

Cookie doesn't work properly in webview in android

Webview cannot accept cookies

Android WebView HTTP Cookies not working in API 21

这就是我在我的活动中启动WebView的方式:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.acceptCookie();
    cookieManager.setAcceptFileSchemeCookies(true);

    WebView webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);

    //webView.getSettings().setPluginState(PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setAllowContentAccess(true);
    if (Build.VERSION.SDK_INT >= 16) {
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    }

    webView.loadUrl("file:///android_asset/index.html");

}

以下是JavaScript createCookie()方法,它在普通浏览器中完美运行:

function createCookie(name, value, days) 
{
    value = value.replace(';', COOKIE_ENCODER);

    if (days>=0) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    //else var expires = "";


    document.cookie = name + "=" + value + expires; // + "; path=/";
}

我也尝试使用CookieSyncManager,但Android Studio建议将其折旧。调用createCookie()方法时,控制台不会显示任何错误,它只是不存储cookie。

修改

以下是readCookie()函数的代码,用于在JavaScript中读取cookie。我认为同样可能存储cookie,但是浏览器在阅读它时遇到了问题:

function readCookie(name) 
{
    //name = name.replace(';',COOKIE_ENCODER);
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0)
        {
            s = c.substring(nameEQ.length, c.length);
            s = s.replace(COOKIE_ENCODER,';');
            return s;
        }
    }
    return null;
}

1 个答案:

答案 0 :(得分:1)

您可以使用window.localStorage而不是Cookie。 https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage