Skip to content

Instantly share code, notes, and snippets.

@DavidBruant
Last active December 20, 2015 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBruant/6199886 to your computer and use it in GitHub Desktop.
Save DavidBruant/6199886 to your computer and use it in GitHub Desktop.
Adding cookie-watcher facility in a WebIDL-compliant browser
// This code is placed under a CC0 licence
// add a setCookieWatcher global
(function(global){
"use strict";
var cookieSetter = Object.getOwnPropertyDescriptor(HTMLDocument.prototype, 'cookie').set;
var watcher;
Object.defineProperty(HTMLDocument.prototype, 'cookie', {
set: function(v){
var oldValue = this.cookie;
cookieSetter.call(this, v);
var newValue = this.cookie;
if(watcher){
try{
watcher(oldValue, newValue);
}
catch(e){}
}
}
})
global.setCookieWatcher = function(w){ watcher = w; }
})(this);
// tests
console.log('cookie', document.cookie);
setCookieWatcher(function(ov, nv){
console.log('cookie changed from', ov, 'to', nv);
});
document.cookie = 'a';
console.log('cookie', document.cookie);
document.cookie = 'b';
console.log('cookie', document.cookie);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment