开发者

Why document.cookie is not working

  var curCookie = name + "=" + value +
    "; expires=" + ATS_getExpire()  +
    "; path=" + path  +
    "; domain=" + domain  ;     
document.cookie = curCookie;
alert("Your Cookie : " + document.cookie);

When i use above code the alert messa开发者_JAVA技巧ge coming as empty. Why document.cookie is coming as empty. Please anybody answer.


See here for a Live Example

You're using ; instead of ,.

Use , to deliminate your cookie values

var curCookie = name + "=" + value + 
    ", expires=" + ATS_getExpire() + 
    ", path=" + path + 
    ", domain=" + domain;

document.cookie = curCookie;
alert("Your Cookie : " + document.cookie);

UPDATE

As of today (2021-08-25), the live example is not consistent accross browsers:

  • Chrome 92.0.4515.159: ❌
  • Edge 92.0.902.78: ❌
  • Opera 77.0.4054.277: ❌
  • Firefox 91.0.2: ✅


I found that ... frustratingly, document.cookie doesn't work when running the page locally in one's browser.

When I uploaded the same page to a website, suddenly all the cookie values worked just fine. I will find out why this is and fill the rest of this answer out later.


Sometimes this can occur if the page is hosted on a domain listed on the public suffix list (e.g. github.io, cloudfront.net). These domains are treated specially by the browser and restrict writing cookies for security reasons.


Try using jQuery Cookie plugin:

jQuery Cookie plugin

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜