How to use (or is it possible) MutationObserver to monitor [removed].pathname change?

前端 未结 3 474
醉梦人生
醉梦人生 2021-01-12 14:52

I wonder if it is possible to use MutationObserver to monitor change in window.location.pathname (or window.location.hash).

相关标签:
3条回答
  • 2021-01-12 15:46

    window.location.path is not part of the DOM, so you can't use MutationObservers on it.

    But you can perform 'dirty checking' :

    function watchPathChanges () {
        var currentPath = window.location.pathname;
        setInterval({
            if(window.location.pathname !== currentPath) {
                currentPath = window.location.pathname;
                //do something when it has changed
            }
        }, 50);
    }
    

    With EcmaScript 7, watching for property changes is supported natively with Object.observe(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe

    0 讨论(0)
  • 2021-01-12 15:47

    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.

    0 讨论(0)
  • 2021-01-12 15:49

    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).

    0 讨论(0)
提交回复
热议问题