1.popstate,但是它是需要浏览器点击前进后退才可以触发
window.addEventListener('popstate', (event) => {
// 在浏览器地址变化时执行的代码
console.log('地址栏变化了:', window.location.href);
});
2.通过MutationObserver,这个的话浏览器地址一点点变化都会监测到,很好用
// 创建一个 MutationObserver 实例
const observer = new MutationObserver((mutationsList, observer) => {
// 当发生变化时执行的代码
console.log("发生了变化");
});
// 配置观察选项
const config = { childList: true, subtree: true, attributes: true };
// 传入目标节点和观察选项,开始观察变化
observer.observe(document.body, config);
// 在某个时刻取消监听
observer.disconnect();
上述代码中的 observer.disconnect()就是用来停止监听的