10

What's the best JS or JQuery-specific approach to monitor a cookie through-out the page life on the browser and trigger an event, when the cookie is' changed?

Satish
  • 6,457
  • 8
  • 43
  • 63

3 Answers3

16

As far as I know, it is not possible to bind a change (or similar) event to a cookie directly. Instead, I would go for this approach:

Create a poller that compares the cookie value to the previously known value every X milliseconds.

// basic functions from the excellent http://www.quirksmode.org/js/cookies.html
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

/////////////////////////////////
// ACTUAL FUN STUFF BELOW
/////////////////////////////////

var cookieRegistry = [];

function listenCookieChange(cookieName, callback) {
    setInterval(function() {
        if (cookieRegistry[cookieName]) {
            if (readCookie(cookieName) != cookieRegistry[cookieName]) { 
                // update registry so we dont get triggered again
                cookieRegistry[cookieName] = readCookie(cookieName); 
                return callback();
            } 
        } else {
            cookieRegistry[cookieName] = readCookie(cookieName);
        }
    }, 100);
}

Usage would then be something like this:

listenCookieChange('foo', function() {
    alert('cookie foo has changed!');
});

Note: this has not been tested and is just a quick demo of how I would approach the problem.

EDIT: I have tested this now and it works. See example :)

Aron Rotteveel
  • 81,193
  • 17
  • 104
  • 128
  • 1
    Note: This is only triggered on cookie change events. I needed to check for **cookie creation** as well and thus modified the code like this: `... if (cookieRegistry[cookieName] || readCookie(cookieName) != null) { ...` – Joel Brewer Sep 05 '14 at 19:56
  • Hi Aron, thanks for this fine! Really, thanks. It's 2017 and Im facing an issue with eslint rule about `consistent-return` for `listenCookieChange()` where `setInterval` is. Could you update your answer to make eslint happy? Disabling eslint works. – Sylar May 28 '17 at 07:58
1

Know what, this helped for something weird. I was trying to use Google Translate (http://translate.google.com/translate_tools?hl=en) on a mobile webapp and everytime the language is changed, it kept inserting a bar at the top as the first child of document.body . I am now tracking the 'googtrans' cookie and doing this

listenCookieChange('googtrans', function() {
    $(document.body).css('top','0px');
});
Vik
  • 347
  • 1
  • 12
0

There is a jQuery plugin for cookies.

http://plugins.jquery.com/project/Cookie

It is not difficult to access the cookies in a html document, they live in document.cookie.

<!-- Add cookie -->
$.cookie('cookieName':'cookieValue');

<!-- get cookie -->
$.cookie('cookieName');

<!-- removecookie -->
$.cookie('cookieName', null);

Additionally there are options arguments for add a cookie, e.g. expiry.

However in reply to your question, I don't actually think you can apply a event listener on to cookies unfortunately.

iain
  • 1,693
  • 13
  • 19
  • 4
    Your code has bad syntax. You are using html comments in javascript and the colon between `'cookieName'` and `'cookieValue'` in the first example needs to be a comma. That may be the reason for the downvote. – benekastah Dec 07 '13 at 00:48