Check whether client’s browser have cookies enabled

Usually we assume that every user have cookies enabled. I cannot find any stats on the number of users who have disabled cookies, but 94% of all browsers have Javascript enabled, so lets assume that en equal number have cookies enabled (I know that the remaining 6% could easily be web crawlers).

What should we do with the remaining 6% then? If the website uses cookies as a shopping basket, it would be a good service to let the user know that he is not able to shop without enabling cookies.

When first investigatig this, I assumed that a server-side solution existed. So I implemented the following code in c#:

if (Request.Browser.Cookies) 
  Response.Write("Your browser supports cookies. You may shop");
  Response.Write("The Browser does not support Cookies. Shopping is not possible.");

Unfortunately this tells me if the browser as such supports cookies, not that cookies are enabled by the user. When using IE7, the code always returns true, since IE7 supports cookies in general. Disabling cookies in IE7 changes nothing.

I used Google to search for the answer, and unfortunately you need to use Javascript to check if the user have enabled cookies in his browser. This website contains the Javascript to use.

I rewrote the Javascript so it writes some text if cookies are enabled, and another text if not:

function CookieSetText(yesText, noText)
  var cookieEnabled=(navigator.cookieEnabled)? true : false
  //if not IE4+ nor NS6+
  if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled)
    cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
  if (cookieEnabled)

 When adding a reference to the script in my HTML header, I can use it from my Sitecore XSLT’s:

<script type="text/javascript">
  CookieSetText('<sc:text field="CookiesEnabled"/>', '<sc:text field="CookiesDisabled"/>');

Th example above writes the text for the current item’s “CookiesEnabled” field if cookies are enabled, or writes from the “CookiesDisabled” field when cookies are disabled.

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in General .NET, Sitecore 5, Sitecore 6 and tagged , . Bookmark the permalink.

1 Response to Check whether client’s browser have cookies enabled

  1. keviv says:

    Tried on IE8, and it does not work.
    Disabled the cookieson IE8 and then open a html page with this code and it did not work.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.