(function(win){
var TabBarPlug=function(options){
this.barTitle='DEMOBAR';
}
TabBarPlug.prototype={
//獲取瀏覽過的地址
getSessionUrl: function(){
return JSON.parse(sessionStorage.getItem('historyUrl') || '[]');
},
//存儲瀏覽歷史地址
setSessionUrl: function (source) {
sessionStorage.setItem('historyUrl', JSON.stringify(source || []));
return true;
},
//測試
setBarTitle: function(pageUrl){
pageUrl=pageUrl.toLowerCase();
if(pageUrl.indexOf('a.html')>-1){
this.barTitle='DEMOA';
}
if(pageUrl.indexOf('b.html')>-1){
this.barTitle='DEMOB';
}
},
//當前頁面和瀏覽歷史最後一條匹配
isCurPage: function (urls) {
var curUrl = location.href;
if (!urls) {
urls = [];
}
var lastUrl = urls[urls.length - 1];
if (lastUrl == curUrl) {
return true;
} else {
return false;
}
},
init: function(){
var historyUrl = this.getSessionUrl();
var curUrl = location.href;
this.setBarTitle(curUrl);
//因爲當執行history.back後,當前頁面會在刷新一次,這時候是不需要加入瀏覽記錄的
if (!this.isCurPage(historyUrl)) {
historyUrl.push(curUrl);
this.setSessionUrl(historyUrl);//存儲瀏覽記錄
}
},
go: function (e) {
e ? e : window.event;
e.preventDefault();
e.stopPropagation();
var historyUrl = this.getSessionUrl();
var that = this;
var backApp = function () {
sessionStorage.removeItem('historyUrl');//移除session
win.close();
};
var back = function () {
//IE history.length=0 其他:fixfox、gg history.length=1
if (that.isCurPage(historyUrl)) {//防止用戶多次點擊
historyUrl.pop();//刪除瀏覽地址
that.setSessionUrl(historyUrl);//存儲瀏覽記錄
//發現在app內嵌的頁面需要延遲執行,否則會出現連續關閉兩個頁面的情況
setTimeout(function () {
history.back();//回退
}, 500);
//回退app
if (historyUrl.length <= 0) {
backApp();
}
}
};
console.log(historyUrl);
back();
}
}
win.TabBarPlug=new TabBarPlug();
})(window);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>a</title>
<style type="text/css">
*{ margin:0; padding:0; }
body{ height: 100%; font-size: 14px; color:#fff; background: #222; }
#back{ font-size: 20px; color: red; }
</style>
</head>
<body>
<div class="box">
lldsjfls<br>
lsdjfls<br>
<a href="b.html">跳轉b頁面</a>
lsdjfls<br>
lsdjfls<br>
<div id="back"> click me to back</div>
</div>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script src="js/tabBar.js"></script>
<script type="text/javascript">
TabBarPlug.init();//每個頁面需要加入這個初始化記錄瀏覽地址
document.getElementById('back').addEventListener('click', function(e){
TabBarPlug.go(e);//執行回退
});
</script>
</body>
</html>