Mahmoud Saleh
Mahmoud Saleh

Reputation: 33605

How to detect that JavaScript and/or Cookies are disabled?

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

Upvotes: 63

Views: 77219

Answers (9)

Noah Solomon
Noah Solomon

Reputation: 1261

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

    console.log(checkCookie());
    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;
    }

Upvotes: 26

James Anderson Jr.
James Anderson Jr.

Reputation: 806

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>

Upvotes: 0

Niresh
Niresh

Reputation: 145

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

Upvotes: 7

PHP Guru
PHP Guru

Reputation: 1527

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>

Upvotes: 4

JimmyLandStudios
JimmyLandStudios

Reputation: 447

// 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);
    }
};

Upvotes: 3

Zymotik
Zymotik

Reputation: 7307

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

Upvotes: 20

Mohamad Hamouday
Mohamad Hamouday

Reputation: 2743

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>

Upvotes: 0

kamal
kamal

Reputation: 149

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>

Upvotes: -1

robjmills
robjmills

Reputation: 18588

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

Upvotes: 90

Related Questions