Paulo
Paulo

Reputation: 7303

Check if the client accepts cookie in javascript?

Is there any way to check if the client accepts cookies only with javascript code?

Upvotes: 17

Views: 9922

Answers (3)

Zameer Khan
Zameer Khan

Reputation: 1196

The cookieEnabled property returns a Boolean value that specifies whether or not cookies are enabled in the browser

<script>
if (navigator.cookieEnabled) {
    // Cookies are enabled
}
else {
    // Cookies are disabled
}
</script>

Upvotes: 7

Ben Lowery
Ben Lowery

Reputation: 344

This should do the trick:

function areCookiesEnabled() {
  document.cookie = "__verify=1";
  var supportsCookies = document.cookie.length >= 1 && 
                        document.cookie.indexOf("__verify=1") !== -1;
  var thePast = new Date(1976, 8, 16);
  document.cookie = "__verify=1;expires=" + thePast.toUTCString();
  return supportsCookies;
}

This sets a cookie with session-based expiration, checks for it's existence, and then sets it again in the past, removing it.

Upvotes: 24

L84
L84

Reputation: 46308

For those who are using jQuery Cookie to manage and create cookies here is a simple way to check for cookies and, after checking for the cookie, run a function based on cookies being enabled or disabled.

//Create Session Cookie
$.cookie('test-for-cookie', '1');

//Test for Session Cookie
var yesCookie = $.cookie('test-for-cookie');
if  (yesCookie == 1) { 
    //Run function if cookies are enabled.
} else{
    //If cookies are not enabled run this function.
} 

jsFiddle of working example.

Upvotes: 2

Related Questions