URL 参数更改时的侦听器事件

use*_*251 9 javascript jquery listener addeventlistener

我有一个带有分页和过滤器的单页应用程序,需要检测当前 URL 何时发生变化。有没有一种简单的方法可以将侦听器添加到当前 URL 并在它更改时触发某些内容?(也没有设置间隔!)

  1. 用户登陆 www.foobar.com
  2. 用户做了某事,网址更改为 www.foobar.com?filter=hello
  3. 我的功能运行

我试过 onhashchange 和 unbeforeunload,两者都与此无关。

window.onbeforeunload = function(e) {
   alert ('url changed!');
};

window.onhashchange = function() { 
alert ('url changed!');  
}
Run Code Online (Sandbox Code Playgroud)

有没有办法向 URL 添加侦听器,并在它发生任何变化时触发某些内容?(再次,单页应用程序,所以没有刷新)

Jer*_*yal 9

您可以使用MutationObserver来监听 URL 变化等:

let previousUrl = '';
const observer = new MutationObserver(function(mutations) {
  if (window.location.href !== previousUrl) {
      previousUrl = window.location.href;
      console.log(`URL changed from ${previousUrl} to ${window.location.href}`);
    }
});
const config = {subtree: true, childList: true};

// start listening to changes
observer.observe(document, config);

// stop listening to changes
// observer.disconnect();
Run Code Online (Sandbox Code Playgroud)

  • 通过像这样使用`MutationObserver`,您不会监听 URL 更改,而是监听 DOM 的更改并尝试捕获 url 的更改作为可能的副作用。但 url 完全有可能发生变化,而 DOM 根本不会发生变化。 (3认同)

klu*_*gjo 7

如果您不想使用 setInterval,则可以覆盖该history.pushState事件:

(function(history){
    const pushState = history.pushState;
    history.pushState = function(state) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
        // Call your custom function here
        return pushState.apply(history, arguments);
    }
})(window.history);
Run Code Online (Sandbox Code Playgroud)

  • 箭头函数不公开 `arguments` 对象,你必须使用 `history.pushState = (state, ...args) => {` 和 `pushState.call(history, state, ...args);` (2认同)