美文网首页
监听浏览器后退事件

监听浏览器后退事件

作者: 芸芸众生ing | 来源:发表于2022-03-01 17:59 被阅读0次
 init() {
      window.history.pushState({ target: "MeanSure", random: Math.random() }, "", location.href);
      window.history.pushState({ target: "Final", random: Math.random() }, "", location.href);
      const option = {
        closeOnPopstate: false,
        confirmButtonText: "留下",
        cancelButtonText: "离开",
        message: "确认离开当前页面吗?"
      };

      async function observer(e) {
        // console.log("popstate", e?.state);
        if (e.state?.target == "MeanSure") {
          try {
            await Dialog.confirm(option);
            stay();
          } catch (error) {
            back();
          }
        }
      }
      //封装的常规操作,回退到上一级
      function back() {
        // console.log("back", history?.state?.target);
        let backCount = history.state.target == "Final" ? -3 : -2;
        history.go(backCount);
      }
      //封装的常规操作,停留在本页面
      function stay() {
        // console.log("stay", history?.state?.target);
        history.go(1);
      }
      window.onpopstate = observer;
    }

相关文章

网友评论

      本文标题:监听浏览器后退事件

      本文链接:https://www.haomeiwen.com/subject/ejqjrrtx.html