I need to trigger a function whenever window.location.href changes but I'm running into problems. I went over the source for various watch
polyfills, but I can't quite follow what was going on with the code.
if (!Object.prototype.watch) {
Object.defineProperty(Object.prototype, "watch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop, handler) {
var
oldval = this[prop]
, newval = oldval
, getter = function () {
return newval;
}
, setter = function (val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
}
;
if (delete this[prop]) { // can't watch constants
Object.defineProperty(this, prop, {
get: getter
, set: setter
, enumerable: true
, configurable: true
});
}
}
});
}
Obviously, I don't know much about the internals of JS or reflection in general. Here is a method that works for title:
var observer = new window.MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
change({title: mutation.target.textContent});
});
});
observer.observe(document.querySelector('head > title'),
{ subtree: true, characterData: true, childList: true });
But I can't specify Location via a query selector and I'm pretty sure it would need to implement the node class for observer to work.