Cookies, also known as web cookies, HTTP Cookies or just cookies, are a mechanism that allow the store of that in the client’s browser. This information is sent by a server to the web browser and then sent back without change each time the browser access that server. Cookies are used for several purposes such authentication, tracking or just to hold specific information, such users preferences in a web site. The idea and name was inspired in the well-known concept “magic cookie” from UNIX.

This mechanism is so common between developers that most of the times we forget to check the client browser support for them. When we develop an application that uses cookies we must check their support to avoid some errors. This can be done in several ways, such with server side scripting. The code bellow shows a simple way to check cookies support with JavaScript.

<script type=”text/javascript”>
var cookiesON = false;
if (typeof navigator.cookieEnabled==”undefined”)
{
//if other than IE4+ and NS6+
var date = new Date();
document.cookie = “checkCookie=”+date.getTime();
cookiesON = (document.cookie.indexOf(“checkCookie”)!=-1)? true : false
}
else
{
//if IE4+ or NS6+
cookiesON = (navigator.cookieEnabled)? true : false;
}

//Do something
if (cookiesON)
alert(‘Cookies ON’);
else
alert(‘Cookies OFF’);
</script>

One problem that comes with the web development is the need to develop cross-browser applications. This way, in the above code you see two different ways of check cookie support in JavaScript.

  • The first one checks cookies on browsers different from IE4+ and NS6+ by trying to put a dummy value in the cookie and read it. If we could read it, is because cookies are enabled. There is no problem by storing the dummy value because this one is removed when the browser is closed. This is the behavior when isn’t specified a expire date.
  • We could use the same verification for all browsers. However, browsers like IE4+ or NS6+ have the cookie support information built-in with a navigator property “cookieEnabled”.
Leave a Reply

Security Code:

Recent comments

Valid XHTML 1.0 Transitional Valid CSS!

Recent posts

2007-2014 © ProTech, All rights reserved | Powered by WS4.org