js修改物理返回键功能

preventBack: function(theurl){
var pushState = window.history.pushState;
//点击物理返回键时,退出到跳转定义首页
if(pushState){
window.history.pushState({a: Math.random()},'', location.href);
window.addEventListener('popstate', function(){
var type = typeof(theurl);
type == 'function' ? theurl() : window.location.href=theurl;
}, !1);
}
}

但是得注意一些ios系统下在APP内嵌的H5网页会出现不明BUG(如链接跳转直接跳了theurl)

当前活动历史项(history entry)改变会触发popstate事件。调用history.pushState()创建新的历史项(history entry),或调用history.replaceState()替换新的历史项(history entry),那么popstate事件的state属性会包含历史项(history entry)状态对象(state object)的拷贝。

需要注意的是调用history.pushState()history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()

不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会

部分浏览器window.addEventListener('popstate',function(){})不会触发

原文地址:https://www.cnblogs.com/lichuntian/p/6387390.html