使用场景:在微信浏览器点击后退按钮,页面弹窗提示用户“确定离开吗”,确定则离开微信,取消则停留在当前页面,隐藏弹窗。

该效果主要是利用js的popstate事件,由于ios和android对页面js脚本运行机制的不同,会出现很棘手的兼容性问题,以下是自己总结出的解决两者兼容性的处理方法:

<script type="text/javascript">
    //在页面初始化时,加入一个空连接
    pushHistory();
    //让窗口监听popstate事件
    window.addEventListener("popstate",function(e){
        if(window.history.state && window.history.state.title && window.history.state.title == 'backalert'){
            //区分android客户端
            var u = navigator.userAgent;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
            if(isAndroid){
                leaveWx();
            }
        }else{
            leaveWx();
        }
    });
    //回退触发的js
    function leaveWx(){
        if(confirm('确定离开吗')){
            if(typeof(WeixinJSBridge) != 'undefined'){
                WeixinJSBridge.call('closeWindow');
            }else{
                window.history.go(-1);
            }
        }else{
                pushHistory();
        }
    }
 
    //在history加入空连接
    function pushHistory(){
        var state={title:"backalert",url:"#"};
        window.history.pushState(state, "", "#");
    };
</script>

 
相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!