How to use (or is it possible) MutationObserver to monitor window.location.pathname change?
Mutation observers observe the DOM, not objects, and are not relevant here.
Object observers cannot observe location.hash
, not because location
is a system object or a security risk, but because hash
is a synthetic property managed internally by the equivalent of getters and setters.
In your case, you don't need any of that. You can watch for hash changes using the popState
event.
window.onpopstate=function() { console.log("foo"); };
location.hash = "bar";
"foo"
I don't know what your intent is in watching for changes in location.pathname
. That will cause a page reload before your handler has a chance to do anything.
No - you cannot use MutationObservers
The new EcmaScript 7 (in preview, draft) is going to have Object.observe
which will allow you to monitor any object. However, that is in not going to work: observing global objects is a security risk and I doubt that any browser will allow that (Chromium issue 494574).
Also, as other pointed out, window.location is a system object (of type Location Object) so it is not covered by Object.observe
.
You can test that with Chrome 43 which already supports Object.observe: kangax.github.io/compat-table/es7/#Object.observe
So the only solution is to watch changes using timeout mechanism or use window.onpopstate
(if you need to monitor only hash).