Last active
December 20, 2015 21:48
-
-
Save DavidBruant/6199886 to your computer and use it in GitHub Desktop.
Adding cookie-watcher facility in a WebIDL-compliant browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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