vue处理关闭浏览器页签和关闭整个浏览器触发事件调后端接口

事项说明 & 建议
🎯 核心事件 beforeunload (用于提示用户), unload (用于发送请求) 
⚠️ 请求方法 推荐使用 fetch (设置 keepalive: true) 或 navigator.sendBeacon(),避免使用异步的axios 
🔍 区分场景 可以尝试通过时间差判断是关闭还是刷新页签,但方法并非完全可靠 
🧹 内存管理 在Vue组件的 beforeDestroy 生命周期中移除事件监听,避免内存泄漏 

实现步骤与代码示例:

1.在Vue组件中添加事件监听
通常在组件的 mounted 生命周期中添加事件监听,并在 beforeDestroy 中移除。

export default {
  data() {
    return {
      beforeUnloadTime: 0,
      gapTime: 0,
      hasUnsavedChanges: true // 根据你的实际业务状态设置
    };
  },
  mounted() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
    window.addEventListener('unload', this.handleUnload);
  },
  beforeDestroy() {
    // 组件销毁时,务必移除监听器
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
    window.removeEventListener('unload', this.handleUnload);
  },
  methods: {
    // ... 其他方法见后续步骤
  }
};

2.处理 beforeunload 事件(可选)

handleBeforeUnload(event) {
  if (this.hasUnsavedChanges) {
    // 以下代码可以触发浏览器默认的确认对话框
    event.preventDefault();
    event.returnValue = ''; // 这是标准属性,但为了兼容旧浏览器,两者都设置
    return '';
  }
},

3.处理 unload 事件并发送请求

方法一:使用 fetch API

handleUnload() {
  // 注意:这里无法处理服务器响应
  fetch('/api/your-logout-endpoint', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ userId: 'user123' }),
    keepalive: true // 关键!确保请求在页面卸载后也能发出
  });
},

方法二:使用 navigator.sendBeacon()

handleUnload() {
  const data = JSON.stringify({ userId: 'user123' });
  // 注意:sendBeacon 默认以 'text/plain' 内容类型发送。
  // 如果需要以 'application/json' 发送,可以使用 Blob
  const blob = new Blob([data], { type: 'application/json; charset=UTF-8' });
  navigator.sendBeacon('/api/your-logout-endpoint', blob);
},

 

posted @ 2025-11-04 11:41  Oopy  阅读(126)  评论(0)    收藏  举报