Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript navigator.cookieEnabled Browser Compatibility

How well supported is navigator.cookieEnabled? Can I safely rely on it for all browsers?

like image 474
dtbarne Avatar asked May 25 '11 13:05

dtbarne


People also ask

What is navigator cookieEnabled?

navigator. cookieEnabled returns a Boolean value that indicates whether cookies are enabled or not. The property is read-only.

How do you check if browser cookies are enabled JavaScript?

To check whether a setting a cookie is enabled in the browser, you can use the cookieEnabled property in the window. navigator global object in JavaScript. The property will return a Boolean true if cookie enabled and return false if not enabled.

Is cookie enabled?

Enabling cookies in Chrome for Android Open Chrome. Go to More menu > Settings > Site settings > Cookies. You'll find the More menu icon in the top-right corner. Make sure cookies are turned on.


2 Answers

I know it's present in at least IE 6 and later, Firefox 1 and later, and Dottoro reports that it is supported by all major browsers. However, it is not part of any DOM specification and therefore is not guaranteed to be available in or properly implemented by all browsers (for instance, mobile browsers with limited DOM implementations).

As some have discovered, IE returns true for navigator.cookieEnabled even if cookies are blocked for the current site. This means that you cannot currently rely on the property at all and you should avoid it completely.

For a complete cross browser cookie support check, you might want to go with something like this:

var cookies = ("cookie" in document && (document.cookie.length > 0 ||
        (document.cookie = "test").indexOf.call(document.cookie, "test") > -1));

Demo: http://codetester.org/31011785

This will return false in browsers that have cookies disabled or don't support the DOM level 2 property document.cookie, which is about as far as you can go in JS.

like image 51
Andy E Avatar answered Sep 22 '22 16:09

Andy E


In a quick test just now (using IE9), it appears that navigator.cookieEnabled still returns true when the browser is blocking cookies for that site.

In other words, cookies are enabled but not for that particular page you are on.

Therefore you need to test for whether cookies actually work when you set them. The correct code should be (modified from Andy E's answer):

var cookies = 
    ("cookie" in document && (document.cookie.length > 0 ||
    (document.cookie = "test").indexOf.call(document.cookie, "test") > -1))

There is really no point in checking navigator.cookieEnabled.

like image 42
mike nelson Avatar answered Sep 21 '22 16:09

mike nelson