window.location.href上的onchange事件

Puc*_*acz 18 javascript jquery

我想在window.location.href链接更改时触发一些Javascript函数.可能吗?

像这样的东西:

$(window.location.href).on('change', function(){
   doSomething();
});
Run Code Online (Sandbox Code Playgroud)

elz*_*lzi 39

你说' 类似 ',给出你可能正在寻找onbeforeunload事件处理程序的示例代码.

来自Mozilla文档:

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这不会检测某些位置事件,例如[hashchange](http://stackoverflow.com/questions/680785/on-window-location-hash-change)或[history manipulation](http://stackoverflow.com /问题/ 824349 /修改最网址没有,重装浮页). (3认同)

小智 12

当对URL锚点部分进行更改(即在之后)时,会发生hashchange事件 #

window.addEventListener('hashchange', function() {

    alert("Hash Changed");

});
Run Code Online (Sandbox Code Playgroud)


Jer*_*yal 10

没有任何内置事件会在所有 url 更改时触发。让我们看看为什么:

window.addEventListener('hashchange',listener)

  • 仅当 URL 中的哈希 (#) 发生更改时才会触发。

window.addEventListener('popstate', listener);

  • 仅当用户单击后退按钮而不是pushState()事件时触发replaceState()。对于SPA站点没用。

window.onbeforeunload()

  • 不适用于SPA网站和 hashchange。

那么,有办法吗?
是的,使用MutationObserver

let previousUrl = "";

const observer = new MutationObserver(() => {
  if (window.location.href !== previousUrl) {
    console.log(`URL changed from ${previousUrl} to ${window.location.href}`);
    previousUrl = window.location.href;
    // do your thing
  }
});
const config = { subtree: true, childList: true };

// start observing change
observer.observe(document, config);
Run Code Online (Sandbox Code Playgroud)