Search code examples
javascriptobject.observe

Object.observe on document.location


I need to execute a js script when the hash of the page changes, I know there are many ways to know when the hash changes like using jQuery

$(window).on('hashchange', function() {
   // do something
});

I tried to use the Object.observe but it didn't work, I just whant to know why it didn't, why the callback doesn't fire after updating the document.location object.

Object.observe(document.location, function(changes) { 
    console.log(changes);
});

Solution

  • document.location along with many other DOM objects fall into the category of host objects which per spec do not have to behave like regular native JS objects. While Object.observe may work for some of these objects, it does not behave reliably and happens not to work for document.location.

    Another example where it does not work is:

    var el = document.createElement('div');
    document.body.appendChild(el);
    Object.observe(el, function(change) { console.log('changed ', change[0].name); })
    
    el.id = "hello";
    el.foo = "bar";