循环阻止H5界面返回

637 阅读1分钟

主要使用了history的popstate监听以及pushstate 通过popstate监听historty的变化来达到界面始终在Final与MeanSure层 从而达不到首次访问界面以实现阻止H5返回 具体实现细节如下所示 image.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>goto1</title>
</head>
<body>
    <h1>这是goto1</h1>
    <a href='goto2.html'>去2</a>
</body>
<script>
     var i = 0;
    doIt()
    console.log(1,history.length)

   //封装的常规操作,跳转到其他页面
   function toUrl(url){
        //首先跳回顶点,防止多次添加记录
        window.history.pushState({target:  "Final",}, "", location.href);
       location.href=url;
    }
 
    //封装的常规操作,回退到上一级
    function back() {
        let backCount=history.state.target == "Final"?-3:-2;
        history.go(backCount);
    }
 
    //封装的常规操作,停留在本页面
    function stay() {
        history.forward();
    }
 
//实际的拦截操作
 function doIt() {
        //此处添加500毫秒延迟,目的是等待历史记录变化之后再添加空地址,使空地址能准确添加到栈顶,防止出错
        setTimeout(() => {
            if (!(history.state && history.state.target == "Final")) {
                window.history.pushState({target: "MeanSure", random: Math.random()}, "", location.href);
                window.history.pushState({target: "Final", random: Math.random()}, "", location.href);
                console.log('添加完成',history.state)
            }
            window.addEventListener("popstate", function (e) {
                console.log('监听到页面发生动作',history.state)
                console.log(5,history.length)
                if (e.state && e.state.target == "MeanSure") {
                    //此处可调用一些自定义的操作,例如弹窗提示之类的,最后根据实际需要可调用上面三个函数中的任何一个,用于决定当前自定义操作完成之后,需要停留在本页面,还是回退,还是跳转到其他页面
                    // doSomething();
                    stay();//如此操作会停留在本页面
                    //back();如此操作会无副作用回退到上一级
                    //toUrl('http://www.baidu.com');如此操作会执行完之定义操作之后跳转到百度
                }
            }, false);
            history.back() //自动触发popstate
        }, 2000);
}
</script>
</html>