Puc*_*acz 18 javascript jquery
我想在window.location.href链接更改时触发一些Javascript函数.可能吗?
像这样的东西:
$(window.location.href).on('change', function(){
   doSomething();
});
elz*_*lzi 39
你说' 类似 ',给出你可能正在寻找onbeforeunload事件处理程序的示例代码.
来自Mozilla文档:
window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};
小智 12
当对URL锚点部分进行更改(即在之后)时,会发生hashchange事件 #
window.addEventListener('hashchange', function() {
    alert("Hash Changed");
});
Jer*_*yal 10
没有任何内置事件会在所有 url 更改时触发。让我们看看为什么:
window.addEventListener('hashchange',listener)
window.addEventListener('popstate', listener);
pushState()事件时触发replaceState()。对于SPA站点没用。window.onbeforeunload()
那么,有办法吗?
是的,使用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);