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)
小智 12
当对URL锚点部分进行更改(即在之后)时,会发生hashchange事件 #
window.addEventListener('hashchange', function() {
alert("Hash Changed");
});
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
37310 次 |
最近记录: |