簡體   English   中英

如何使用(或可能)MutationObserver來監視window.location.pathname的變化?

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

我想知道是否可以使用MutationObserver監視window.location.pathname(或window.location.hash)中的更改。

變異觀察者觀察DOM,而不是對象,並且在這里不相關。

對象觀察者無法觀察location.hash不是因為location是系統對象或安全風險,而是因為hash是由getter和setter等效內部管理的合成屬性。

在您的情況下,您不需要任何這些。 您可以使用popState事件監視哈希更改。

window.onpopstate=function() { console.log("foo"); };

location.hash = "bar";
"foo"

我不知道你在觀察location.pathname變化時的意圖。 這將導致在您的處理程序有機會執行任何操作之前重新加載頁面。

不 - 你不能使用MutationObservers

新的EcmaScript 7(預覽,草稿)將具有Object.observe ,它允許您監視任何對象。 但是,這是行不通的 :觀察全局對象是一種安全風險,我懷疑任何瀏覽器都會允許這樣做( Chromium issue 494574 )。

另外,正如其他指出的那樣,window.location是一個系統對象(類型為Location Object),因此它不被Object.observe覆蓋。

您可以使用已支持Object.observe的Chrome 43對其進行測試: kangax.github.io/compat-table/es7/#Object.observe

所以唯一的解決方案是使用超時機制觀察更改或使用window.onpopstate (如果您只需要監視哈希)。

window.location.path不是DOM的一部分,因此您不能在其上使用MutationObservers。

但你可以執行'臟檢查':

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

使用EcmaScript 7, Object.observe()本身支持查看屬性更改: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM