js 监听返回键 利用pushState

5 篇文章 0 订阅
5 篇文章 0 订阅

 我的开发工作主要是做移动端广告的页面,为了留住更多的用户,我们需要监听浏览器的返回键,在用户返回时,弹出弹窗来进一步提供选项来分流客户。(监听关闭键无法自定义弹窗)

     使用的方法就是利用pushState(基于jq,改成原生不难,自己动手。。。。)。

     先上代码

if (window.history && window.history.pushState) {
  //监听浏览器前进或后退
    $(window).on('popstate', function () {
        $('.outModals').hide() //outModals  弹窗class
        $('.outModals').remove()
     //当浏览器前进时不弹弹窗
        if(location.hash.indexOf('myback')==-1){
            stateInit()
        }
    });  
    //防止浏览器刷新造成多个历史记录
    if(location.hash.indexOf('myback')==-1||location.hash==''){
        window.history.pushState(number, null, '#myback'); 
        window.history.forward(1);
    }
}else {
    //统计下因为兼容问题所存在的用户
    addTongJi()
}
function stateInit(){

    var html='弹窗的dom class=outModals '
    $('body').append(html)
          // 继续
        $('.outModals_sure').unbind('click').bind('click',function () {
            addTongJi('continue')
            $('.outModals').hide()
            $('.outModals').remove()
            window.history.forward(1);
        })
         //离开
        $('.outModals_out').unbind('click').bind('click',function () {
            addTongJi('break')
            $('.outModals').hide()
            $('.outModals').remove()
            window.history.go(-1)
        })
    
}

pushState 添加一条 history 实体作为替代原来的 history 实体 

$(window).on('popstate', function () {}) 监听history 实体 变化。

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值