How to detect that JavaScript and/or Cookies are disabled?
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>
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
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;
}
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