7

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)?

Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
  • 2
    I haven't tested it in all browsers, but the whole point of having jQuery and jQuery plugins is to be cross-browser compatible. Also, "all browsers" is a little wide; I would consider IE6 and Opera to be at the fringe. – Robert Harvey Jan 08 '10 at 18:26
  • Unfortunately for this client I need to have IE6. Opera I would like, but I guess I can live without. – Darryl Hein Jan 08 '10 at 18:41

3 Answers3

10

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.

Community
  • 1
  • 1
Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
  • 2
    Yes I think It will work for every browser, here is another code sample http://blog.nickburwell.com/2009/05/check-if-cookies-are-enabled-on-client.html – Manoj Singh Feb 23 '11 at 16:13
1

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.

Shawn Steward
  • 6,773
  • 3
  • 24
  • 45
1

I like this 1 liner function:

function cookiesEnabled() {
    return $.cookie('check', 'valid', { expires: 1 }) && $.cookie('check') == 'valid';
}
wayofthefuture
  • 8,339
  • 7
  • 36
  • 53