55

How to detect that JavaScript or Cookies are disabled in the user's browser and notify him any help ?

Mahmoud Saleh
  • 31,861
  • 113
  • 313
  • 484

9 Answers9

84

For checking cookies you can use:

function checkCookie(){
    var cookieEnabled = navigator.cookieEnabled;
    if (!cookieEnabled){ 
        document.cookie = "testcookie";
        cookieEnabled = document.cookie.indexOf("testcookie")!=-1;
    }
    return cookieEnabled || showCookieFail();
}

function showCookieFail(){
  // do something here
}


// within a window load,dom ready or something like that place your:
checkCookie();

And for checking JavaScript use a <noscript> tag with some kind of message inside

Demur Rumed
  • 371
  • 4
  • 17
robjmills
  • 17,839
  • 14
  • 71
  • 118
  • 6
    Note that this won't run when JS is disabled :) – BalusC Jan 05 '11 at 12:21
  • 12
    if testcookie was written you should delete it after. – Vitim.us Nov 13 '11 at 20:48
  • Why test that `typeof navigator.cookieEnabled=="undefined"`? Would it not be correct that navigator.cookieEnabled was actually set to be a false type? – Alex Edwards Feb 11 '14 at 18:07
  • 3
    This won't work with IE with privacy option set to `High`. In this mode `navigator.cookieEnabled` is `true` but `document.cookie` is always empty. The best is to remove the first test of checkCookie(): `function checkCookie(){document.cookie="testcookie"; var cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false; return (cookieEnabled)?true:showCookieFail(); }` – Charles Aug 17 '15 at 12:50
  • This check fails in Safari 9. See https://github.com/Modernizr/Modernizr/commit/33f00fbbeb12e92bf24711ea386e722cce6f60cc for a better solution. – Noah Solomon May 11 '17 at 18:53
  • 1
    Fails to detect correctly in IE11, you can test here: http://sveinbjorn.org/cookiecheck – Zymotik Jan 30 '18 at 12:03
  • Note: In Chrome(other browsers not tested) running a local html file(`file://` protocol) without the flag `--enable-file-cookies`, `nagigator.cookieEnabled` returns `true` but `document.cookie` ignores all writings and always returns an empty string. – VainMan Oct 25 '20 at 07:34
23

Update (6/25/18):

A lot of these posts, including mine, are taking snippets from Modernizr. They will all eventually become outdated as the Modernizr code gets updated.

I think the best answer to this question should be to use Modernizr directly.

if (Modernizr.cookies) {
  // supported
} else {
  // not-supported
}

Original Answer (5/11/17):

This is taken straight from Modernizr and works in more browsers than other solutions in this post.

https://github.com/Modernizr/Modernizr/commit/33f00fbbeb12e92bf24711ea386e722cce6f60cc

function checkCookie(){
    // Quick test if browser has cookieEnabled host property
    if (navigator.cookieEnabled) return true;
    // Create cookie
    document.cookie = "cookietest=1";
    var ret = document.cookie.indexOf("cookietest=") != -1;
    // Delete cookie
    document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    return ret;
}
Noah Solomon
  • 1,133
  • 12
  • 23
17

As the cookie detection didn't work in IE 11, I suggest the Modernizr approach:

function areCookiesEnabled() {
    try {
      document.cookie = 'cookietest=1';
      var cookiesEnabled = document.cookie.indexOf('cookietest=') !== -1;
      document.cookie = 'cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
      return cookiesEnabled;
    } catch (e) {
      return false;
    }
}

https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cookies.js

mcmimik
  • 639
  • 7
  • 24
Zymotik
  • 3,378
  • 1
  • 28
  • 41
3
// Example[1]: if ( hasCookies() )
/**
* @hasCookies:  Check if cookie's are Enabled
* @param  {none} ''
* @return {BOOLEAN} true|false
*/
function hasCookies() {
return (navigator.cookieEnabled);
}

 // Example[2]: if ( JLS.TEST.COOKIE() )
// Java Pattern ( How to write usable JS)
/** @namespace JLS classes and functions. */
var JLS = JLS || {};
/**
* TEST utility
* @namespace JLS
* @class TEST
*/
JLS.TEST = {

/**
* @public-method COOKIE
* @COOKIE  Check if cookie's are Enabled
* @return {BOOLEAN} true|false
*/
 COOKIE: function () {
    //Change this (library). Not main.js (Algorithm)
    return (navigator.cookieEnabled);
    }
};
2

This is the easiest way

if (navigator.cookieEnabled) {
document.write("Cookies Enabled");
} else 
{
document.write("Oops Cookies Not Enabled");
}
Check if Cookies Enabled in Your Browser:  
<br />
Niresh
  • 79
  • 1
  • 12
2

Assuming JavaScript is enabled, this will tell you if cookies are enabled or not. Works in old browsers.

// returns 1 or 0 instead of true or false. Returns null if inconclusive.
function cookiesEnabled() {
    var i, j, cookies, found;
    if (navigator.cookieEnabled===false) return 0;
    document.cookie = 'testcookiesenabled=1';
    for (i=0; i<2; i++) {
        found = false;
        cookies = document.cookie.split(';');
        j = cookies.length;
        while(j--) {
            while (cookies[j].charAt(0)==' ') {// trim spaces
                cookies[j] = cookies[j].substring(1);
            }
            if (cookies[j].indexOf('testcookiesenabled=')==0) {
                found = true;
                break;
            }
        }
        if (!found) {
            return i;
        }
        // Delete test cookie.
        document.cookie = 'testcookiesenabled=; expires=Thu, 01 Jan 1970 00:00:01 GMT';
    }
    // Results inconclusive.
}

To display a message only when JavaScript is disabled use

<noscript>JavaScript is disabled. Please enabled JavaScript.</noscript>
PHP Guru
  • 964
  • 4
  • 15
0

This function can view error message for users and also can stop script executing and it can return cookies status.

function IS_Cookies_Enabled(Show_Message, Stop_Script)
{
    if(Show_Message == undefined){
        Show_Message = true;
    }

    if(Stop_Script == undefined){
        Stop_Script = false;
    }


    var Cookie_Status = navigator.cookieEnabled;
    if (!Cookie_Status)
    { 
        document.cookie = "Test";
        Cookie_Status = document.cookie.indexOf("Test") != -1;
        // Delete test cookies
        document.cookie = "Test=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";

    }

    if((!Cookie_Status) && (Show_Message))
    {
        document.getElementsByTagName('body')[0].innerHTML = "<div style='width: 600px; max-width: 100%; margin: 100px auto;'><h1 style='color: red'>Cookies Required</h1><p style='font-size: 18px;'>Cookies are not enabled on your browser. <br>Please enable cookies in your browser preferences to continue.</p><strong>Sylingo</strong>";
    }

    if((!Cookie_Status) && (Stop_Script))
    {
        throw new Error('Cookies is disabled');
    }
    return Cookie_Status;
}

To use it:

IS_Cookies_Enabled(true, true);  // Will stop script and view error message

IS_Cookies_Enabled(true, false);  // Just view error message

$Cookies_Status = IS_Cookies_Enabled(false, false);  // return cookies status

And for checking JavaScript use:

<noscript>
Javascript is not enabled on your browser. 
</noscript>
Mohamad Hamouday
  • 1,024
  • 14
  • 17
0

This JavaScript function has always worked for me:

if (typeof areCookiesAllowed !== 'function')
    {
        function areCookiesAllowed()
            {
                var cookies_allowed = navigator.cookieEnabled;

                if (!cookies_allowed)
                    {
                        try
                            {
                                var cur_dt = new Date();
                                var cur_tm = cur_dt.getTime();

                                document.cookie = 'cookie_test_' + cur_tm + '=1';
                                cookies_allowed = document.cookie.indexOf('cookie_test_' + cur_tm + '=') !== -1;
                                document.cookie = 'cookie_test_' + cur_tm + '=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
                            }
                        catch(err)
                            {
                                return false;
                            };
                    };

                return cookies_allowed;
            };
    };

if (typeof areCookiesAllowed !== 'function')
 {
  function areCookiesAllowed()
   {
    var cookies_allowed = navigator.cookieEnabled;

    if (!cookies_allowed)
     {
      try
       {
        var cur_dt = new Date();
        var cur_tm = cur_dt.getTime();

        document.cookie = 'cookie_test_' + cur_tm + '=1';
        cookies_allowed = document.cookie.indexOf('cookie_test_' + cur_tm + '=') !== -1;
        document.cookie = 'cookie_test_' + cur_tm + '=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
       }
      catch(err)
       {
        return false;
       };
     };

    return cookies_allowed;
   };
 };
  
var result_elmt = document.getElementById("result");
var result;

if (areCookiesAllowed() === true)
 {
  result = 'Congratulations! Cookies are enabled in this Web Browser and on this website!';
 }
else
 {
  result = 'Aww Snap! Unfortunatly cookies are NOT enabled in this Web Browser or are disabled on this website.';
 };

result_elmt.innerHTML = result;
alert(result);
<span id="result"></span>
-1

Try <noscript>...</noscript> tags it works partial to check if JavaScript is enabled or not.

<script type="application/javascript">
    document.write("This text would be displayed if JavaScript is enabled");
</script>
<noscript>
    This text would be displayed if JavaScript is not enabled
</noscript>
Dan Jones
  • 1,077
  • 10
  • 19
kamal
  • 139
  • 6
  • 6
    The ` – Rory O'Kane Jul 10 '13 at 15:21