监听浏览器地址栏的改变

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

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

亲测好用,推荐给大家

代码如下

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

  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);

// 设置监听函数
window.history.onpushstate = function(e) {
  console.log('通过pushState改变了URL:' + e.url);
};
window.history.onreplacestate = function(e) {
  console.log('通过replaceState改变了URL:' + e.url);
};

在这里插入图片描述

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

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

如果不在意是哪种情况,全部复制粘贴到浏览器运行即可

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值