将代码放到需要禁止回退的页面即可
主要代码
$(function () {
//防止页面后退
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
})
使用路由方法
mainView.router.back(options)
- 这个方法会触发一个反向的动画并回到上一个页面,也就是浏览历史上的回退
完整代码:
var historyLength = 0;
var timestamp=new Date().getTime();
function forbidHistoryBack(e) {
var now=new Date().getTime();
window.setTimeout(function () { historyLength=0; },2000);
if(historyLength>=1 && now-timestamp<2000) {
history.back();
if(isWeiXin() && !!WeixinJSBridge) WeixinJSBridge.call('closeWindow');
} //2秒内连续点击2次则退出myApp
else { //2秒内前1次后退按Framework7的访问页面历史
historyLength++;
timestamp = now;
$.toast('再按一次退出');
if($('.picker-modal:visible').length>0) jglApp.closeModal($('.picker-modal:visible').get($('.picker-modal:visible').length-1)) //逐层关闭 Picker Modal
else if($('.popup:visible').length>0) jglApp.closeModal($('.popup:visible').get($('.popup:visible').length-1)) //逐层关闭 Popup
else if($('.panel-left:visible').length>0) jglApp.closePanel(); //关闭最近打开的侧栏
else mainView.router.back(); //触发一个反向的动画并回到上一个页面
history.pushState(null, null, document.URL); //禁止回退离开首页
}
}
//判断是否微信浏览器的函数
function isWeiXin(){
//window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息,这个属性可以用来判断浏览器类型
var ua = window.navigator.userAgent.toLowerCase(); //通过正则表达式匹配ua中是否含有MicroMessenger字符串
if(ua.match(/MicroMessenger/i) == 'micromessenger') return true;
else return false;
}
$(function () {
//防止页面后退
history.pushState(null, null, document.URL);
window.addEventListener("popstate",forbidHistoryBack, false);
});