use*_*251 9 javascript jquery listener addeventlistener
我有一个带有分页和过滤器的单页应用程序,需要检测当前 URL 何时发生变化。有没有一种简单的方法可以将侦听器添加到当前 URL 并在它更改时触发某些内容?(也没有设置间隔!)
我试过 onhashchange 和 unbeforeunload,两者都与此无关。
window.onbeforeunload = function(e) {
alert ('url changed!');
};
window.onhashchange = function() {
alert ('url changed!');
}
Run Code Online (Sandbox Code Playgroud)
有没有办法向 URL 添加侦听器,并在它发生任何变化时触发某些内容?(再次,单页应用程序,所以没有刷新)
您可以使用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)
如果您不想使用 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)
| 归档时间: |
|
| 查看次数: |
7883 次 |
| 最近记录: |