views:

261

answers:

6

Exactly what are the restrictions for handling browser cookies from javascript? Can I check if cookies are enabled for example?

+2  A: 

You write a cookie and try to read back: this way, you'll know if cookies are enabled.

jldupont
A: 

To answer the question of the title, yes you can add or modify a cookie with javascript. You can read an example here.

eKek0
post the example :D
CrazyJugglerDrummer
There appears to be a bug in that code, using getDate() where getTime() should be used.
Bratch
+2  A: 

Yes! Read this great article about it

And as for testing whether they are enabled. I like jldupont's answer.

jessegavin
Good article with working scripts.
Bratch
+1  A: 

you can use navigator.cookieEnabled but I'm not sure if it's supported by all browsers.

For more information about cookies, check this

Soufiane Hassou
A: 

Can I check if cookies are enabled for example?

Yes, but not as easily as you think. navigator.cookieEnabled is a very general flag which does not cover exactly under what circumstances you may set a cookie.

For example, it's possible for session cookies to be allowed but persistent cookies blocked. So you're not really going to know whether a cookie-set will succeed unless you go ahead and try it, by setting a dummy document.cookie and then reading document.cookie back to see if it took.

In many browsers a persistent cookie will be downgraded to a session cookie when persistent cookies are disabled. But not IE, which will simply block it. You can try to detect that by setting both a persistent and a session cookie to document.cookie and seeing which if any survives.

bobince
A: 

The W3Schools JavaScript Cookies code has a bug in it. In the function setCookie this line:

exdate.setDate(exdate.getDate()+expiredays);

JavaScript Date Object Properties:
getDate() - Returns the day of the month (from 1-31)
...
getTime() - Returns the number of milliseconds since midnight Jan 1, 1970
...

getDate() plus the number of days is not going to work. I think it should be something like this:

expire = expiredays * 1000 * 60 * 60 * 24; // convert to milliseconds
var exdate = new Date( today.getTime() + (expire) );

The cookie libraries at TechPatterns.com Javascript Cookie Script Get Cookie, Set Cookie, Delete Cookie Functions work better (#1 in Google results isn't always the best).

I tested code from both pages in IE8 and the first one caused my cookie to have an expire date of 1/1/2038 1:00 AM. The code from the second example set my cookie expire date to exactly 1 day from the time I tested it, just as expected.

Bratch