Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a message only if cookies are disabled in browser? [duplicate]

How to show a message only if cookies are disabled in browser? like http://stackoverflow.com show if JavaScript is disabled.

like image 364
Jitendra Vyas Avatar asked Jan 30 '10 08:01

Jitendra Vyas


1 Answers

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;
}
like image 63
bobince Avatar answered Oct 11 '22 13:10

bobince