首页 前端知识 vue实现浏览器关闭或刷新弹窗提示(beforeunload/unload)

vue实现浏览器关闭或刷新弹窗提示(beforeunload/unload)

2024-06-26 00:06:12 前端知识 前端哥 765 804 我要收藏

vue实现浏览器关闭或刷新弹窗提示

  • 一、推荐代码
  • 二、错误情况说明
    • 1.在beforeunload事件里面加alert
    • 2.在一个没有焦点的 iframe 或 frame 浏览器会阻止 beforeunload 弹窗
    • 3.无法触发destroyed/beforedestroyed/deactivated
    • 4.能触发beforeRouteEnter,但不能触发beforeRouteUpdate、beforeRouteLeave


vue实现浏览器关闭或刷新弹窗提示
也可以在时候强制保存记录或执行其他操作。

一、推荐代码

export default {
  data () {
    return {
    }
  },
  
  mounted() {
    window.addEventListener('beforeunload', e => this.beforeUnloadHandler(e))
    window.addEventListener('unload', e => this.unloadHandler(e))
  },
  destroyed() {
    window.removeEventListener('beforeunload', e => this.beforeUnloadHandler(e))
    window.removeEventListener('unload', e => this.unloadHandler(e))
  },
  methods: {
    beforeUnloadHandler(e) {
      e.returnValue = '确定离开页面吗?';
      return " ";
    },
    unloadHandler(e) {
      e.returnValue = '确定离开页面吗?';
      return " ";
    }
  }
}

代码说明:
有些浏览器会限制在 beforeunload 事件中触发 alert,confirm 或 prompt 等弹出式的用户交互。这是为了防止滥用这些弹窗干扰用户的操作。
虽然在 beforeunload 事件中弹出这些窗口通常被浏览器禁止,但你仍然可以在这个事件中修改 event.returnValue 的值来显示一个提示给用户。但这种方式无法自定义内容,只能显示浏览器默认的文本。

beforeunload 事件在即将离开当前页面(刷新或关闭)时触发。
unload 事件在即将离开当前页面(刷新或关闭)时触发。

二、错误情况说明

1.在beforeunload事件里面加alert

代码:

window.onbeforeonload = function(){
window.alert("A");
}

报错:
Blocked alert() during beforeunload.

2.在一个没有焦点的 iframe 或 frame 浏览器会阻止 beforeunload 弹窗

报错:
Blocked attempt to show a 'beforeunload' confirmation panel for a frame that never had...
说明:
用户有操作了点击界面后再刷新/关闭窗口才会触发。

3.无法触发destroyed/beforedestroyed/deactivated

原因:keepAlive设置为true时,
不会触发beforedestroyed,destroyed等方法
而且,deactivated 钩子在使用 keep-alive 组件缓存时触发,而页面刷新会清除所有的缓存,所以在这种情况下,deactivated 钩子也不会执行。

4.能触发beforeRouteEnter,但不能触发beforeRouteUpdate、beforeRouteLeave

原因:

  • beforeRouteEnter:在进入该路由前被调用,通常用于在组件渲染前获取数据等操作。
  • beforeRouteUpdate:在当前路由改变,但是该组件被复用时调用。
  • beforeRouteLeave:在离开当前路由时被调用。

如果 beforeRouteEnter 能够触发而其他两个却无法触发,可能是因为路由的变化并不会触发组件的重新渲染,而是进行了复用。beforeRouteUpdate 和 beforeRouteLeave 都是针对组件复用时触发的。

转载请注明出处或者链接地址:https://www.qianduange.cn//article/13593.html
标签
评论
发布的文章

JSON、Ajax

2024-07-27 22:07:31

JsonNode、ObjectNode和ArrayNode

2024-07-27 22:07:30

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!