DevPub
Free Mousepad

How Google Works

How Google WorksA look at the myths and facts about Google, and what you should know about Google's inner workings. Continue Reading

Search Engines and You: Getting Crawled

Search Engines and You: Getting CrawledHow to get your newly launched web site to be indexed by search engines and how directories can help you. Continue Reading

Determine if Cookies Are Enabled

Use a few simple lines of JavaScript to verify if cookies are accepted by the target web browser.

On Sunday, January 6th 2008 at 05:28 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.3 with 6 votes)

Even though over 99% of the browsers today accept cookies happily, sometimes we cannot ignore the few Internet users out there who have cookies disabled for one reason or the other. Although typically webmasters don't want to or cannot find a workaround for not using cookies, notifying the visitor that his cookies are disabled and functionality might suffer, is something that can be easily done with only a few lines of JavaScript.

<script type="text/javascript">

function TakesCookies()

{

    var GetsCookie = (navigator.cookieEnabled)?true:false

    // If the browser does not support cookie check

    if(typeof navigator.cookieEnabled=="undefined" && !cookieEnabled)

    {

        // Try setting up a test cookie

        document.cookie = "SampleCookie";

        // And see if it got set successfully

        GetsCookie = (document.cookie.indexOf("SampleCookie")!=-1)?true:false

    }

    return GetsCookie;

}

 

function CookieTest()

{

    // TakesCookies is now set to the proper value

    if(TakesCookies())

    {

        alert("This browser accepts cookies");

    }

    else

    {

        alert("This browser does not accept cookies");

    }

}

</script>


The code is pretty much self explanatory because of all the comments, and the overall idea is that two tests are being performed - one is the checking of a simple property that will tell us if cookies are enabled or not, and one is a fail safe for the browsers that do not support that property. The fail safe consists in attempting to set a cookie and checking if that cookie got set successfully or not.

The CookieTest() function is simply something you can call from your onLoad event of <body> as such:

<body onload="CookieTest()">


It will get all the little wheels of this code in motion.

Rate Rate this tutorial

Comment Comment on this tutorial
Name: Email:
Message:

Comment Current Comments
by pglewis on Tuesday, April 8th 2008 at 05:25 PM

It occurs to me that a paranoid user who has cookies disabled will likely have js disabled as well. This snake eats it's own tail.

by selvasekhar on Tuesday, April 22nd 2008 at 02:44 AM

good one

by selvasekhar on Tuesday, April 22nd 2008 at 02:46 AM

good one