Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

How to check if cookies are enabled

Suggested Videos
Part 69 - Store multiple key value pairs in a cookie
Part 70 - Set and get multiple cookies in JavaScript
Part 71 - Update and delete cookies



In this video we will discuss, how to check if cookies are enabled.



Most websites rely on browser cookies being enabled. For example, if you have disabled cookies and if you try to log into gmail.com, you will receive an error message saying - Oops! Your browser seems to have cookies disabled. Make sure cookies are enabled or try opening a new browser window. 

How to check if cookies are enabled

The following JavaScript code detects if cookies are enabled. Most modern browser's support navigator.cookieEnabled property. 

This property returns true if cookies are enabled and false if cookies are disabled. Some old browsers don't support this property. 

For those browsers that don't support navigator.cookieEnabled property, we are setting "mytestcookie" and then reading again to make sure cookies are enabled. If we are not able to read "mytestcookie" then we know that cookies are disabled.

<div id="msg"></div>
<script type="text/javascript">
    function cookiesEnabled()
    {
        var cookiesEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == "undefined" && !cookiesEnabled)
        {
            document.cookie = "mytestcookie";
            cookiesEnabled = (document.cookie.indexOf("mytestcookie") != -1) ? true : false;
        }

        return cookiesEnabled;
    }

    if (cookiesEnabled())
    {
        document.getElementById("msg").innerHTML = "Cookies enabled";
    }
    else
    {
        document.getElementById("msg").innerHTML = "Cookies disabled";
    }
</script>

JavaScript tutorial

No comments:

Post a Comment

It would be great if you can help share these free resources