返回攔截
功能:從廣告進入到落地頁后,給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); }