Quantcast
Channel: K's cluttered loft - JavaScript
Viewing all articles
Browse latest Browse all 10

JavaScript Cookie Check

$
0
0

It's strange to see that today in 2012 browser cookies are still making trouble. It shouldn't be that difficult to check with JavaScript if cookies are enabled in the browser. The non-standard navigator.cookieEnabled flag works correctly in Chrome, Firefox, Opera and Safari but Internet Explorer is simply lying to us! It supports this flag (It's not null or undefined) but it is always set to true! So we still need hacks for this browser. It's also strange that I wasn't able to find a working hack on the Internet. So I wrote my own:

/**
 * Checks if browser supports cookies.
 *
 * @return {boolean}
 *             True if browser supports cookies, false if not.
 */
function supportsCookies()
{
    var cookieEnabled = navigator.cookieEnabled;

    // When cookieEnabled flag is present and false then cookies are disabled.
    // Thanks to IE we can't trust the value "true".
    if (cookieEnabled === false) return false;

    // Internet Explorer is lying to us. So we have to set a test cookie
    // in this browser (We also do it for strange browsers not supporting
    // the cookieEnabled flag). But we only do this when no cookies are
    // already set (because that would mean cookies are enabled)
    if (!document.cookie && (cookieEnabled == null || /*@cc_on!@*/false))
    {
        // Try to set a test cookie. If not set then cookies are disabled
        document.cookie = "testcookie=1";
        if (!document.cookie) return false;

        // Remove test cookie
        document.cookie = "testcookie=; expires=" + new Date(0).toUTCString();
    }

    // Well, at least we couldn't find out if cookies are disabled, so we
    // assume they are enabled
    return true;
};

Let's explain what this code is doing:

  • When the navigator.cookiesEnabled flag is present and is false then we definitely know that cookies are disabled. All major browsers except Internet Explorer will stop right here when cookies are blocked.
  • When navigator.cookiesEnabled flag is not present (maybe some really old browser) or when Internet Explorer is deteced (Checked with JScript conditional compilation) then a test cookie is set. But we only do this when there are no cookies already set (Because when there is already a cookie then cookies can't be disabled). When our test cookie can be read again then cookies are enabled, otherwise they are disabled.

The code works in IE7-10, Firefox 17, Chrome 23, Opera 12 and Safari 6.

What a shame that code like this is still needed in 2012...


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images