浏览器history操作实现一些功能

返回拦截

功能:从广告进入到落地页后,给history增加一个页面,拦截返回动作

主要用到的是h5中的history对象,使用了pushState,和replaceState来操作。

并且加入了一些条件判断,包括 history.state, history.state.page,history.state.entered。

以上这些方法可以实现按需操作history对象。

但history操作后,按返回按钮其实是只更新url地址,不刷新页面的,最终的刷新页面,是用 window.onpopstate 监听,

在判断条件符合后,手动去reload一次页面。

以下就是实现该功能的代码:

 1 /**
 2  * @note    从广告渠道过来后,按返回按钮时的拦截功能
 3  * @author  kangxufeng <kangxufeng@duiba.com.cn>
 4  * @create  17/08/08
 5  * @des     1.url中存在a_tuiaId时,激活拦截功能
 6  *          2.插入state:{page:'intercept'}的页面
 7  *          3.当前页面state:{page:'current'}
 8  */
 9 
10 ;
11 (function() {
12   var intercetpUrl = '/';
13 
14   $(function() {
15     if (history.pushState) {
16       // 支持pushState
17       if (!history.state) {
18         // 未插入页面
19         if (isToIntercept()) {
20           initReturn();
21         }
22       } else {
23         //已插入页面
24         window.onpopstate = function(e) {
25           if (history.state && history.state.page == 'current') {
26             location.reload();
27           } else if (history.state && history.state.page == 'intercept') {
28             if (!history.state.entered) {
29               // 未拦截
30               history.state.entered = true;
31               updateTimes(function() {
32                 location.reload();
33               });
34             } else {
35               // 已拦截
36               history.go(-1);
37             }
38           }
39         }
40       }
41     }
42 
43   })
44 
45   function initReturn() {
46     if (!history.state) {
47       var thisLocation = location.href;
48       history.replaceState({page:'intercept',entered:false},'',intercetpUrl);
49       history.pushState({page:'current'},'',thisLocation);
50     }
51     window.onpopstate = function () {
52       // location.reload();
53       if(history.state && history.state.page == 'intercept') {
54         if (!history.state.entered) {
55           // history.state.entered = true;
56           history.replaceState({page:'intercept',entered:true},'',intercetpUrl);
57           updateTimes(function() {
58             location.reload();
59           });
60         }
61       }
62     }
63   }
64 
65   function updateTimes(callback) {
66     callback & callback();
67   }
68 
69   function isToIntercept() {    
70     if (getparams('a_tuiaId')) {
71       // 存在a_tuiaId,表示从广告进来
72       return true;
73     } else {
74       return false;
75     }
76   }
77 
78   function getparams(name) {
79     var regexS = "[\?&]" + name + "=([^&#]*)";
80     var regex = new RegExp(regexS);
81     var results = regex.exec(location.href);
82 
83     if (results === null) return "";
84     else return results[1];
85   }
86 })(Zepto);

返回上上个页面

功能:首页打开商品详情页B,判断售罄跳转到售罄页C,在C页面点返回时略过B直接回到首页。

B.js:

jumpToEmpty: function() {
  history.replaceState({page: 'soldout'}, '', '/item/soldOut');
  location.reload();
}

C.js:

window.onpopstate = function() {
  history.go(-1);
}
原文地址:https://www.cnblogs.com/woodk/p/7302651.html