js监听浏览器返回,pushState,popstate 事件,window.history对象小白常识
在WebApp或浏览器中,会有点击返回、后退、上一页等按钮实现自己的关闭页面、调整到指定页面、确认离开页面或执行一些其它操作的需求。可以使用 popstate 事件进行监听返回、后退、上一页操作。
一、简单介绍 history 中的操作
1.window.history.back(),后退
2.window.history.forward(),前进
3.window.history.go(num),前进或后退指定数量历史记录
4.window.history.pushState(state, title, utl),在页面中创建一个 history 实体。直接添加到历史记录中。
5.window.history.replaceState(),修改当前的 history 实体。
6.popstate 事件,history 实体改变时触发的事件。
7.window.history.state,会获得 history 实体中的 state 对象。
二、使用方法
取消默认的返回操作:
1.添加一条 history 实体作为替代原来的 history 实体
function pushHistory() {
// 第一个实体
var state = {
title: "index",
url: "https://www.cnblogs.com/smallclown/"
};
window.history.pushState(state, "index", location.href);
// 第二个实体
state = {
title: "index",
url: "https://www.cnblogs.com"
};
window.history.pushState(state, "index", location.href);
// 第三个实体 不要以为最后的空实体没有用 可以解决上来就执行popstate的问题 相当于炮灰
tate = {
title: "index",
url:""
};
window.history.pushState(state, "index", "");
}
// history.pushState(state, title, url);
// history.replaceState(state, title, url); 替换
2.监听 popstate 事件
function addHandler() {
pushHistory();
window.addEventListener("popstate", function(e) {
location.href = window.history.state.url;
}
});
//或者
window.onpopstate=function(e){
location.href = window.history.state.url;
}
}
addHandler();
PS:
每次返回都会消耗一个 history 实体,若用户选择取消离开,则需要继续 pushState 一个实体 ;
如果把地址换了一个你想去的地址,就形成了一个简单的网页劫持