Reputation: 221
I have a jQuery-based web app. My requirement is fairly simple: I want to use jQuery to find out if the user has enabled or disabled cookies in their web browser. I'm aware that there's a plugin available which can be used to create/retrieve/delete/update a cookie. But, is there a way jQuery can detect the user agent's settings?
Upvotes: 22
Views: 30814
Reputation: 20940
Why are you testing with the property cookieEnabled
? just try to create a cookie and check if it's done. And in case cookies work, delete the test created cookie.
function are_cookies_enabled()
{
document.cookie="testcookie=valid";
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
if(cookieEnabled){
document.cookie = "testcookie=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
}
return cookieEnabled;
}
Upvotes: 0
Reputation: 408
You can simply set a test_cookie when loading your page. then delete if it is set, else alert('please enable cookies...');
<script>
jQuery(document).ready(function()
{
var TEST_COOKIE = 'test_cookie';
jQuery.cookie( TEST_COOKIE, true );
if ( jQuery.cookie ( TEST_COOKIE ) )
{
jQuery.cookie( TEST_COOKIE, null ); // delete the cookie
alert( 'Good news, cookies are enabled.' );
}
else
{
alert( 'Cookies not enabled. Please enable and try again.' );
}
}
</script>
Upvotes: -2
Reputation: 9455
I like this 1 liner function:
function cookiesEnabled() {
return $.cookie('check', 'valid', { expires: 1 }) && $.cookie('check') == 'valid';
}
Upvotes: 1
Reputation: 8190
Internet Explorer (version 10, at least) always returns true for navigator.cookieEnabled
. Here's a method to work around this:
function areCookiesEnabled() {
var cookieEnabled = navigator.cookieEnabled;
// When cookieEnabled flag is present and false then cookies are disabled.
if (cookieEnabled === false) {
return false;
}
// try to set a test cookie if we can't see any cookies and we're using
// either a browser that doesn't support navigator.cookieEnabled
// or IE (which always returns true for navigator.cookieEnabled)
if (!document.cookie && (cookieEnabled === null || /*@cc_on!@*/false))
{
document.cookie = "testcookie=1";
if (!document.cookie) {
return false;
} else {
document.cookie = "testcookie=; expires=" + new Date(0).toUTCString();
}
}
return true;
}
Upvotes: 7
Reputation: 9298
The simplest way is to check the navigator
's property which contains the browser's information. Reference
You could use navigator.cookieEnabled === true
to detect the browser's support for cookie.
Upvotes: 5
Reputation: 382881
You don't need jQuery for that, you can use vanilla Javascript:
function are_cookies_enabled()
{
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
{
document.cookie="testcookie";
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
}
return (cookieEnabled);
}
http://sveinbjorn.org/cookiecheck
Upvotes: 41