|
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. |