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

前端 未结 3 473
醉梦人生
醉梦人生 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

提交回复
热议问题