监听浏览器地址栏的改变,路由监听

887 阅读1分钟

是否遇到业务代码改变了浏览器地址,并且页面也刷新了,需要找出改变了浏览器地址的代码,做出业务逻辑的调整,但是发现代码逻辑杂乱、罪孽深重,不知从何下手?

这时候,我们可以通过监听浏览器地址栏的改变,断点查看调用栈,找到改变地址栏的代码,然后进行调整

亲测好用,推荐给大家

2024年08月29日 星期四 更新

代码如下

要监听浏览器地址栏的变化后触发断点,可以控制台运行以下三种方法:

  1. 使用popstate事件:这个事件在浏览器历史记录发生变化时触发。
window.addEventListener('popstate', function(event) {
  console.log('浏览器历史记录改变,新的URL为:' + document.location);
  debugger;  // 断点
});
  1. 监控hashchange事件:当URL中的哈希部分(即#后面的部分)发生变化时触发。
window.addEventListener('hashchange', function() {
  console.log('哈希值改变,新的URL为:' + document.location);
  debugger;  // 断点
});
  1. 封装pushStatereplaceState方法:通过重写这两个方法,可以在调用这些方法时自动执行监听操作。
(function(history){
    var pushState = history.pushState;
    history.pushState = function(state, title, url) {
        debugger;  // 断点
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state, title: title, url: url});
        }
        return pushState.apply(history, arguments);
    };

    var replaceState = history.replaceState;
    history.replaceState = function(state, title, url) {
        debugger;  // 断点
        if (typeof history.onreplacestate == "function") {
            history.onreplacestate({state: state, title: title, url: url});
        }
        return replaceState.apply(history, arguments);
    };
})(window.history);

浏览器地址断点.gif

这三种方法可以根据你的具体需求选择使用,比如你需要捕获所有通过脚本操作导致的地址栏改变,可以选择第三种方法

如果你关心的是用户通过浏览器前进后退触发的变化,使用第一种方法即可

如果想分辨哪种情况,第三个复制粘贴到浏览器运行即可