是否遇到业务代码改变了浏览器地址,并且页面也刷新了,需要找出改变了浏览器地址的代码,做出业务逻辑的调整,但是发现代码逻辑杂乱、罪孽深重,不知从何下手?
这时候,我们可以通过监听浏览器地址栏的改变,断点查看调用栈,找到改变地址栏的代码,然后进行调整
亲测好用,推荐给大家
代码如下
要监听浏览器地址栏的变化后触发断点,可以控制台运行以下三种方法:
- 使用
popstate
事件:这个事件在浏览器历史记录发生变化时触发。
window.addEventListener('popstate', function(event) {
console.log('浏览器历史记录改变,新的URL为:' + document.location);
debugger; // 断点
});
- 监控
hashchange
事件:当URL中的哈希部分(即#
后面的部分)发生变化时触发。
window.addEventListener('hashchange', function() {
console.log('哈希值改变,新的URL为:' + document.location);
debugger; // 断点
});
- 封装
pushState
和replaceState
方法:通过重写这两个方法,可以在调用这些方法时自动执行监听操作。
(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);
};
这三种方法可以根据你的具体需求选择使用,比如如果你需要捕获所有通过脚本操作导致的地址栏改变,可以选择第三种方法。
如果你关心的是用户通过浏览器前进后退触发的变化,使用第一种方法即可。
如果不在意是哪种情况,全部复制粘贴到浏览器运行即可