vue處理關(guān)閉瀏覽器頁(yè)簽和關(guān)閉整個(gè)瀏覽器觸發(fā)事件調(diào)后端接口
| 事項(xiàng) | 說(shuō)明 & 建議 |
|---|---|
| ?? 核心事件 | beforeunload (用于提示用戶), unload (用于發(fā)送請(qǐng)求) |
| ?? 請(qǐng)求方法 | 推薦使用 fetch (設(shè)置 keepalive: true) 或 navigator.sendBeacon(),避免使用異步的axios |
| ?? 區(qū)分場(chǎng)景 | 可以嘗試通過時(shí)間差判斷是關(guān)閉還是刷新頁(yè)簽,但方法并非完全可靠 |
| ?? 內(nèi)存管理 | 在Vue組件的 beforeDestroy 生命周期中移除事件監(jiān)聽,避免內(nèi)存泄漏 |
實(shí)現(xiàn)步驟與代碼示例:
1.在Vue組件中添加事件監(jiān)聽
通常在組件的 mounted 生命周期中添加事件監(jiān)聽,并在 beforeDestroy 中移除。
export default { data() { return { beforeUnloadTime: 0, gapTime: 0, hasUnsavedChanges: true // 根據(jù)你的實(shí)際業(yè)務(wù)狀態(tài)設(shè)置 }; }, mounted() { window.addEventListener('beforeunload', this.handleBeforeUnload); window.addEventListener('unload', this.handleUnload); }, beforeDestroy() { // 組件銷毀時(shí),務(wù)必移除監(jiān)聽器 window.removeEventListener('beforeunload', this.handleBeforeUnload); window.removeEventListener('unload', this.handleUnload); }, methods: { // ... 其他方法見后續(xù)步驟 } };
2.處理 beforeunload 事件(可選)
handleBeforeUnload(event) { if (this.hasUnsavedChanges) { // 以下代碼可以觸發(fā)瀏覽器默認(rèn)的確認(rèn)對(duì)話框 event.preventDefault(); event.returnValue = ''; // 這是標(biāo)準(zhǔn)屬性,但為了兼容舊瀏覽器,兩者都設(shè)置 return ''; } },
3.處理 unload 事件并發(fā)送請(qǐng)求
方法一:使用 fetch API
handleUnload() { // 注意:這里無(wú)法處理服務(wù)器響應(yīng) fetch('/api/your-logout-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ userId: 'user123' }), keepalive: true // 關(guān)鍵!確保請(qǐng)求在頁(yè)面卸載后也能發(fā)出 }); },
方法二:使用 navigator.sendBeacon()
handleUnload() { const data = JSON.stringify({ userId: 'user123' }); // 注意:sendBeacon 默認(rèn)以 'text/plain' 內(nèi)容類型發(fā)送。 // 如果需要以 'application/json' 發(fā)送,可以使用 Blob const blob = new Blob([data], { type: 'application/json; charset=UTF-8' }); navigator.sendBeacon('/api/your-logout-endpoint', blob); },

浙公網(wǎng)安備 33010602011771號(hào)