js监听浏览器后退事件

导语:日常开发中,网站需求是用户点击浏览器的返回事件,网站会执行某些操作。

先来看看效果:

代码一:

 1 $(function(){
 2 
 3 pushHistory();
 4 
 5 window.addEventListener("popstate", function(e) {
 6 
 7 alert("监听到返回按钮事件啦");
 8 
 9 //根据自己的需求实现自己的功能
10 
11 //window.location.href = 'https://www.baidu.com'
12 
13         },false);
14 
15 function pushHistory() {
16 
17 var state = {
18 
19 title:"title",
20 
21 url:"#"
22 
23 };
24 
25 window.history.pushState(state,"title","#");
26 
27 }
28 
29 });

 

 

代码二:

 1 $(document).ready(function (e) {
 2 
 3 var counter =0;
 4 
 5 if (window.history && window.history.pushState) {
 6 
 7 $(window).on('popstate', function () {
 8 
 9 window.history.pushState('forward',null,'#');
10 
11 window.history.forward(1);
12 
13 // alert("不可回退");  //如果需在弹框就有它
14 
15                 self.location="orderinfo.html";//如查需要跳转页面就用它
16 
17             });
18 
19 }
20 
21 window.history.pushState('forward',null,'#');//在IE中必须得有这两行
22 
23         window.history.forward(1);
24 
25 });

 

posted @ 2021-11-01 14:42  名曰大神  阅读(1740)  评论(0编辑  收藏  举报