How to show a message only if cookies are disabled in browser? like http://stackoverflow.com show if JavaScript is disabled.
There used to be a JavaScript navigator.cookieEnabled
interface, but today browsers have a much wider range of cookie controls than just ‘enabled’/‘disabled’, including session/persistent options, first-party/third-party, site-specific settings and P3P. So sniffing this property is of little use now.
No, the only reliable way to find out whether you can set a cookie is to try to set it, and see if it's still there. Another wrinkle is that whilst many browsers will downgrade a persistent cookie to a session cookie when the user's privacy controls don't allow them, IE will not.
If you try to set a persistent cookie in IE when they are disabled, the cookie will simply be thrown on the floor. This can catch you out if you use a simple session-cookie checker, find cookies are enabled, and then try to set a persistent cookie. And you can't get away with trying to set as a session cookie and a persistent cookie, because when you set a persistent cookie in IE with persistent cookies disabled, it will even delete the existing session cookie of the same name. Oh IE!
So if you need to set a persistent cookie but make do with session where persistent isn't available, you'd have to use this first to find out what you're allowed to do:
// Find out what cookies are supported. Returns:
// null - no cookies
// false - only session cookies are allowed
// true - session cookies and persistent cookies are allowed
// (though the persistent cookies might not actually be persistent, if the user has set
// them to expire on browser exit)
//
function getCookieSupport() {
var persist= true;
do {
var c= 'gCStest='+Math.floor(Math.random()*100000000);
document.cookie= persist? c+';expires=Tue, 01-Jan-2030 00:00:00 GMT' : c;
if (document.cookie.indexOf(c)!==-1) {
document.cookie= c+';expires=Sat, 01-Jan-2000 00:00:00 GMT';
return persist;
}
} while (!(persist= !persist));
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With