在Android WebView中设置Cookie

时间:2014-11-26 07:26:08

标签: android cookies webview android-webview

我正在尝试为Android webview启用Cookie,但它不适用于我 这是我试过的

CookieManager cookieManager = CookieManager.getInstance(); 
CookieSyncManager.createInstance(this);

webView = (WebView) findViewById(R.id.webView);
cookieManager.setAcceptCookie(true); 
cookieManager.acceptCookie();
CookieSyncManager.getInstance().startSync();
WebSettings settings = webView.getSettings();  
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);  
settings.setDefaultZoom(ZoomDensity.FAR);
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true); 
settings.setRenderPriority(RenderPriority.HIGH);
settings.setAppCacheEnabled(true);
settings.setAllowFileAccess(true);
settings.setAllowContentAccess(true);
settings.setDomStorageEnabled(true);

这是JS

function getCookie(cname) {

    var name = cname + "=";
    var ca = document.cookie.split(';');
    alert(ca);
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

更新

以下是我设置Cookie的方法

function setCookie(cname, cvalue) {

    var domain = document.domain;
    var currentURL = document.URL;
        if (currentURL.substr(0, 4) == 'file') {
    alert("in offline cookie set");
     document.cookie = cname + "=" + cvalue + "; path=/;" + " domain=file://";
      }
      else{
     document.cookie = cname + "=" + cvalue + "; path=/;" + " domain=" + domain;
      }
}

4 个答案:

答案 0 :(得分:0)

尝试设置:

CookieManager.getInstance().setAcceptCookie(true);

答案 1 :(得分:0)

初始化网页浏览后,您必须在之后致电CookieManager.getInstance().setAcceptCookie(true); 。我想这是你的问题!

答案 2 :(得分:0)

我知道,您正在尝试设置file:// cookies。在创建WebView或访问CookieManager之前,请尝试此方法:http://developer.android.com/reference/android/webkit/CookieManager.html#setAcceptFileSchemeCookies(boolean)

请阅读此方法的文档!

答案 3 :(得分:0)

我没有任何文档可供参考,但由于某些(可能是安全性)原因,无法通过webView从本地文件URL方案(例如:file:// ...)获取Cookie。

所以我认为唯一的解决方案是构建本地HttpServer(例如:NanoHttpd)并为本地文件添加vhost。