Check If The Client Accepts Cookie In Javascript?
Is there any way to check if the client accepts cookies only with javascript code?
Solution 1:
This should do the trick:
functionareCookiesEnabled() {
document.cookie = "__verify=1";
var supportsCookies = document.cookie.length >= 1 &&
document.cookie.indexOf("__verify=1") !== -1;
var thePast = newDate(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.
Solution 2:
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>
Solution 3:
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 Cookievar yesCookie = $.cookie('test-for-cookie');
if (yesCookie == 1) {
//Run function if cookies are enabled.
} else{
//If cookies are not enabled run this function.
}
Post a Comment for "Check If The Client Accepts Cookie In Javascript?"