PDA

View Full Version : cookies in JS cross browser?


homerUK
05-26-2003, 01:08 PM
hey,

I've written some code which remembers a users choice while they are on my site....I use document.cookie to set elements on the page.

My question is this: what happens if the user has cookies disabled, and how can you detect this? Also ... are cookies cross browser? or does NS use a different method of calling them?

Thanks for any advice!

HairyTeeth
05-26-2003, 10:45 PM
if(document.cookie){
//cookies enabled
}else{
//cookies disabled
}

As far as I know, all browsers use the same syntax to bake a cookie. I prefer lamingtons.

liorean
05-26-2003, 10:53 PM
That doesn't work. document.cookie is available for all cookies savvy browsers even if cookies are turned off. It just doesn't work. The only way to make sure is to set and read a cookie directly afterwards. If it exists, the browser has cookies enabled. I've got a cookie handler with a function that checks for cookie support on my website, if you are lazy :)

HairyTeeth
05-26-2003, 11:17 PM
Hmmm..I'd follow lioreans advice anytime. With the following code:

if(document.cookie)
alert("I support cookies")
else
alert("Nope, not baking this time")

IE5 alerts appropriately, Opera 7.10 doesn't seem to understand document.cookie, whether cookies are enabled or not.

:confused:

liorean
05-26-2003, 11:54 PM
Hmm, yeah, but you're using a shortcut. document.cookies exists, but it's empty. An empty string evaluates to false. Remember that document.cookies might have been set BEFORE the cookies were disabled. That way you would be able to read but not write them.

Also, this being my personal opinion, I disagree with using JavaScript's automatic typecasting like that. It's dirty coding and shouldn't be used, especially as it might come back and bite you when you least expect it if you ever use another "curly block" language such as C/C++.

realisis
05-27-2003, 03:58 AM
er, um...

navigator.cookieEnabled

returns true or false ... recognized by IE and NS6...

realisis
05-27-2003, 04:19 AM
er, make that IE, NS6 and 7 (and other modern Gecko offshoots), and Opera 7 (but not OP6)...

so that prolly about 95% of the browsers out there???

btw, this one's a boolean, not a string...