onbeforeunload 使用

710 阅读1分钟

onbeforeunload 事件可以用在页面刷新前,页面关闭前,进行提示判断等相关操作。页面首次渲染后,不进行任何操作直接关闭浏览器 tab 或者 F5 进行刷新,此时页面不会有任何提示。

######只有在页面渲染完毕后,页面进行操作后才有提示效果。

如:

  1. 页面加载完后在页面空白处进行一次点击,再执行 F5 刷新或执行关闭 tab 操作时,浏览器提示窗口弹出。
  2. 直接点击页面中的 <a> 标签进行页面跳转,浏览器提示窗口弹出。

注意: 浏览器将统一显示弹出框中的提示消息, 如 Chrome 将显示 “您是否要离开此网站?您所做的更改可能无法保存”

MDN 详情说明:developer.mozilla.org/en-US/docs/…

index1.html 例子来自 MDN

<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>
  hi
  <script type="text/javascript">
  window.onbeforeunload = function(e) {
    var dialogText = 'Dialog text here';
    e.returnValue = dialogText;
    return dialogText;
  };
  </script>
</body>

</html>

index2.html 例子来自 w3schools

<!DOCTYPE html>
<html>

<body onbeforeunload="return myFunction()">
  <p>This example demonstrates how to assign an "onbeforeunload" event to a body element.</p>
  <p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
  <a href="https://www.w3schools.com">Click here to go to w3schools.com</a>
  <script>
  function myFunction() {
    return "Write something clever here...";
  }
  </script>
</body>

</html>

vue 中使用 onbeforeunload

 mounted () {
    window.onbeforeunload = function (e) {
      return ''
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.progressVisible) {
      this.$confirm('系统可能不会保存您所做的更改。', '离开此页面?', {
        confirmButtonText: '离开',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        next()
      })
    } else {
      next()
    }
  },
  beforeDestory () {
    window.onbeforeunload = null
  }