Is using the jQuery Cookie plugin a valid way of testing to see if cookies are enabled?
I have a site that we require the user to have enabled JavaScript and cookies before they can login to the site. (The JS part is done and works perfectly.) At the moment, we have been been setting a cookie and then redirect the user to another page (in PHP). This has worked fine, but now we开发者_开发问答 have a bunch of people that have bookmarked the page we are redirecting to, which of course doesn't have the cookie set and therefore doesn't allow them to login.
So I'm trying to find another solution to check for the cookie and I'm thinking of using the jQuery Cookie plugin. I'm wondering if it's compatible in all browsers (when JS is enabled of course)?
Thxs Shawn for your answer, but unfortunately because browsers don't always send the referrer, it isn't reliable enough to be able to use it every time. Because if it isn't set, then you kind of end up in a loop.
The one other solution that I thought of was to redirect to a completely separate page, which in itself checks to see if cookies are enabled (by redirecting to itself). If cookies are enabled, it would redirect back to the original page. If they are not, then it would redirect to a page about the problem. I think that should work, but I'm not sure.
In the end, I tried the jQuery Cooke plugin in IE 6, 7, and 8, Safari 4, Google Chrome 4, Firefox 3.5, Opera 10.2 and on a few different configurations and it worked in all of them. Here is the code I'm using:
$.cookie('test_cookie', 'cookie_value', { path: '/' });
if ($.cookie('test_cookie') == 'cookie_value') {
// cookie worked, set/enable appropriate things
}
It's not perfect, but I'm thinking it will work in 95% of cases. Otherwise, it will fail and just not allow them to do anything.
You could check the referrer of the page and if it's not your home page, you can redirect them there. If the referrer is your home page and there's no cookie set, you'll know they do not have cookies enabled.
I like this 1 liner function:
function cookiesEnabled() {
return $.cookie('check', 'valid', { expires: 1 }) && $.cookie('check') == 'valid';
}
精彩评论