views:

53

answers:

2

I want to test with JavaScript whether the browser supports cookies or not. The following code works with Internet Explorer 8 and Firefox 3.6 but not with Google Chrome 5.

function areCookiesEnabled() {
  document.cookie = "__verify=1";
  var supportsCookies = document.cookie.length > 1 &&
                        document.cookie.indexOf("__verify=1") > -1;
  var thePast = new Date(1976, 8, 16);
  document.cookie = "__verify=1;expires=" + thePast.toUTCString();
  return supportsCookies;
}

if(!areCookiesEnabled()) 
    document.write("<p>Activate cookies!</p>");
else
    document.write("<p>cookies ok</p>");

Chrome displays the message "Activate cookies!" regardless of my cookie settings. But if I disallow cookies, Chrome tells me that a cookie could not be set.

Any idea how to test cookie availability with JavaScript in Chrome?

+1  A: 

The only reliable way to tell if cookies are enabled is to set one, and check for its existence on the next request. Server-side code required.

Josh Stodola
I wonder about the fragile cookie handling of Chrome and therefore implemented a cookie test on the server side.
deamon
A: 

I'm not sure why the code doesn't work, but you really can simplify your code which will help pin down the problem:

function areCookiesEnabled() {
  document.cookie = "__verify=1;expires=" + new Date(1976, 8, 16).toUTCString();
  return  (document.cookie.length > 1);
}

if(!areCookiesEnabled()) 
    document.write("<p>Activate cookies!</p>");
else
    document.write("<p>cookies ok</p>");

Also, here is an excellent overview of Javascript cookies, it might help you pin it down.

Tom Gullen
That doesn't work, since (at least) Firefox doesn't accept expired cookies. By the way: why `document.cookie.length > 1` and not `>=`?
deamon
Why are you setting the expiry date to the past? (Didn't notice that originally). It doesn't matter what test length you specify because you are testing if it equals '__verify=1' which is a lot more characters than 1 ;)
Tom Gullen
I thought `document.cookie.length` were the number of the available cookies. Setting to the past is to remove the cookie after the test.
deamon