JS原生后退拦截代码,兼容所有浏览器

在生活中,当我们浏览网页时会发现在某些界面中,当我们点击后退后。当前网页并没有按照我们所期望的那样正常后退,而是留在了原页面,亦或是跳转到了另一个新的页面中去了!

作为一名开发人员,如果有这样一个需求放在你眼前。那么你该如何实现禁止浏览器网页的后退效果呢?

先上代码,有兴趣的朋友可以看下下面的代码简要解释:

<script language="javascript">
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/stealingyourhistory");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/stealingyourhistory") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
alert("点击后退弹出此提示!")
},0);
}
}, false); }(window, location));
</script>

history.pushState()和history.replaceState() 均为Html5新增的两个方法:

history.pushState方法接受三个参数:

state:一个与指定网址相关的状态对象,popstate事件触发时,该对象会传入回调函数。如果不需要这个对象,此处可以填null。

title:新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null。

url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。 

history.replaceState方法的参数与pushState方法一模一样,区别是它修改浏览历史中当前纪录。

UC浏览器后退不能正常解决方法,将setTimeout的0改成800或者比这更大值。

具体也可以查看本博客另一篇文章《UC浏览器js后退拦击不生效怎么办?解决方案!

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!