IOS 微信返回按钮事件控制弹层关闭还是返回上一页

在微信公共号内绑定域名后或微信内打开第三方链接跳转非单页面网站时,经常会有弹层Modal的需求,此时如果用户习惯性点击微信自带的返回“<”按钮,就会跳转回上一页或退出网站,而为了避免这种不好的误操作,需要手动“监听返回”,经过本人多次验证场景可满足有弹层时页面按钮返回和微信返回的双方式都隐藏弹层Modal而不返回,而无弹层时可直接返回上一页,下面就看代码实现:

//打开弹层Modal
openModal = ()=>{
    //你的弹出弹层的代码,如modal.show()之类的;

    //
    this.pushNewState();
    //添加监听
    window.addEventListener("popstate", this.yourEventListener.bind(this), false);
}

//新push一个state
pushNewState = ()=>{
    var state = {title: "title", url: "#"};
    window.history.pushState(state, "", "");  
}

//监听返回执行的函数
yourEventListener = (arg1,argN,...)=>{
    //移除监听
    window.removeEventListener("popstate", this.yourEventListener.bind(this), false);
   //关闭你的弹层,如modal.hide()之类的语句

   //如果当前state等于新push的state则退一步state
   if (window.history.state != null) {
       window.history.back();
   }
}

以上就是全部实现代码,需要注意两点:

1、当弹层有自带的关闭或隐藏按钮时,应改写其执行函数 或 使用自定义的按钮并调用 this.yourEventListener(arg)来执行关闭弹层,否则隐藏弹层后页面停留在新push的state,此时点返回需要点击两次才会有效;

2、在 this.yourEventListener 中添加debugger 调试会发现,如果多次弹层,即使使用了  window.removeEventListener("popstate", this.yourEventListener.bind(this), false); 在关闭弹层时依然会调用多次 this.yourEventListener 执行,目前不清楚为什么,希望有明白的可以留言讨论下,但这并不影响使用效果。

猜你喜欢

转载自www.cnblogs.com/jying/p/10547733.html