优化 刷新页面不在重复播报 离开和登录提示
This commit is contained in:
@@ -1527,10 +1527,14 @@
|
||||
}
|
||||
|
||||
// ── 退出房间 ─────────────────────────────────────
|
||||
let leaveRequestInFlight = false;
|
||||
|
||||
async function leaveRoom() {
|
||||
// 标记主动离开,pagehide 里不重复发 beacon
|
||||
window._manualLeave = true;
|
||||
clearTimeout(visibilityTimer);
|
||||
if (leaveRequestInFlight) {
|
||||
return;
|
||||
}
|
||||
|
||||
leaveRequestInFlight = true;
|
||||
|
||||
try {
|
||||
await fetch(window.chatContext.leaveUrl + '?explicit=1', {
|
||||
@@ -1551,42 +1555,30 @@
|
||||
}, 500);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ── 关闭/离开页面时自动调用 leave,结算勤务时长 ──────────────────────
|
||||
// 使用 sendBeacon 确保浏览器关闭时请求也能发出(比 fetch 更可靠)
|
||||
// 注意:用 pagehide 而非 beforeunload,避免 Chrome 触发原生「离开网站」确认框
|
||||
function sendLeaveBeacon() {
|
||||
if (window._manualLeave) {
|
||||
return;
|
||||
} // 主动调用 leaveRoom() 时不重复发
|
||||
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
|
||||
if (!csrfToken || !window.chatContext?.leaveUrl) {
|
||||
async function notifyExpiredLeave() {
|
||||
if (leaveRequestInFlight) {
|
||||
return;
|
||||
}
|
||||
const data = new FormData();
|
||||
data.append('_token', csrfToken);
|
||||
navigator.sendBeacon(window.chatContext.leaveUrl, data);
|
||||
|
||||
leaveRequestInFlight = true;
|
||||
|
||||
try {
|
||||
if (!window.chatContext?.expiredLeaveUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
await fetch(window.chatContext.expiredLeaveUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'application/json'
|
||||
},
|
||||
credentials: 'same-origin'
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
// pagehide:页面关闭/浏览器关闭/刷新均触发,且不会弹原生确认框
|
||||
window.addEventListener('pagehide', sendLeaveBeacon);
|
||||
|
||||
// visibilitychange:切换到后台标签超过30秒也结算(防止长期挂机不算时长)
|
||||
let visibilityTimer = null;
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) {
|
||||
// 切到后台,30秒后结算
|
||||
visibilityTimer = setTimeout(sendLeaveBeacon, 30 * 1000);
|
||||
} else {
|
||||
// 切回来,取消结算
|
||||
clearTimeout(visibilityTimer);
|
||||
visibilityTimer = null;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
// ── 掉线检测计数器 ──
|
||||
let heartbeatFailCount = 0;
|
||||
@@ -1607,6 +1599,7 @@
|
||||
|
||||
// 检测登录态失效
|
||||
if (response.status === 401 || response.status === 419) {
|
||||
await notifyExpiredLeave();
|
||||
window.chatDialog.alert('⚠️ 您的登录已失效(可能超时或在其他设备登录),请重新登录。', '连接警告', '#b45309');
|
||||
window.location.href = '/';
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user