js拦截安卓手机物理退回键

注意:addEventListener()和removeEventListener()需要调用同一个函数

错误用法示例:函数写法虽然一样,但是实际上调用的不是同一个函数

   window.addEventListener('popstate', function (event) {
        window.history.go(-2);
   });
   window.removeEventListener('popstate', function (event) {
        window.history.go(-2);
   });

正确用法: 

   componentDidMount(){
        //拦截安卓回退按钮
        let me = this;
        // 页面载入时使用pushState插入一条历史记录
        // history.pushState(null, null, location.href);
        window.addEventListener('popstate', me.backRouter);
    }
    //组件移除
    componentWillUnmount(){
        // console.log('componentWillUnmount')
        let me = this;
        //在addEventListener()和removeEventListener()中用的是相同的函数backRouter
        window.removeEventListener('popstate',me.backRouter)
    }
    //返回自定义的路由
    backRouter(){
        window.history.go(-2);
    }

history.back()和history.go()的区别

go(-1): 返回上一页,原页面表单中的内容会丢失;history.go(-1):后退+刷新;history.go(1) :前进

back(): 返回上一页,原页表表单中的内容会保留; history.back():后退 ; history.back(0) 刷新; history.back(1):前进 

如果用back 会保留之前页面的内容,看到的效果就是在回退时中间的页面会闪一下,用go就不会出现中间的页面闪现的问题

转载于:https://my.oschina.net/linxiaoxi1993/blog/3029520

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值