Framework7开发H5App如何禁止回退离开首页

 

将代码放到需要禁止回退的页面即可

主要代码

$(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);
});

 

转载于:https://my.oschina.net/peaksoho/blog/2989396

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值