Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why document.cookie is not working

Tags:

javascript

  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 message coming as empty. Why document.cookie is coming as empty. Please anybody answer.

like image 493
pavan Avatar asked Jul 21 '11 10:07

pavan


3 Answers

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: ✅
like image 130
Raynos Avatar answered Oct 16 '22 17:10

Raynos


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.

like image 31
Sean Munson Avatar answered Oct 16 '22 17:10

Sean Munson


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.

like image 30
krd Avatar answered Oct 16 '22 17:10

krd