zoukankan      html  css  js  c++  java
  • 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 执行,目前不清楚为什么,希望有明白的可以留言讨论下,但这并不影响使用效果。

  • 相关阅读:
    DIY 作品 及 维修 不定时更新
    置顶,博客中所有源码 github
    openwrt PandoraBox PBR-M1 极路由4 HC5962 更新固件
    使用 squid 共享 虚拟专用网至局域网
    第一次参加日语能力测试 N5
    libx264 libfdk_aac 编码 解码 详解
    开发RTSP 直播软件 H264 AAC 编码 live555 ffmpeg
    MFC Camera 摄像头预览 拍照
    http2 技术整理 nginx 搭建 http2 wireshark 抓包分析 server push 服务端推送
    plist 图集 php 批量提取 PS 一个个切
  • 原文地址:https://www.cnblogs.com/jying/p/10547733.html
Copyright © 2011-2022 走看看