Check if the client accepts cookie in javascript?

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

Answers:

Answer

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.

Answer

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

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.