禁用浏览器后退按钮

场景:今天在项目中遇到一种场景,需要禁用浏览器返回按钮,防止用户误操作。考虑试用一下history的新伙伴,history.pushState(),popstate事件

尝试:在各大网友的谋略中,用的最多的版本

history.pushState(null, null, document.URL);
$(window).on('popstate', function() {
history.pushState(null, null, document.URL);
});

果然不错,chrome和Firefox运行良好!

然后,填坑之路漫长啊,IE10+不给力啊,在IE中,url改变是不会触发popstate事件,只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()!这样就不能够使用history.pushState()来抵消用户点击后退按钮。

 

解决办法:还好history还有一个hashchange事件,考虑一下两者的结合

在chrom和firefox中使用

history.pushState(null, null, document.URL);
$(window).on('popstate', function() {
history.pushState(null, null, document.URL);
});

在IE中使用两者:

history.pushState(null, null, document.URL);
$(window).on('popstate', function() {
history.pushState(null, null, document.URL);
});

$(window).on('hashchange', function() {
history.pushState(null, null, document.URL);
});

 

posted on 2017-03-09 11:45 evenBoy 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/evenBoy/p/6524917.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值