Commit 0f428801 authored by 水玉婷's avatar 水玉婷
Browse files

feat:修复页面刷新请求不中断bug

parent 51762e54
......@@ -36,12 +36,16 @@ export class SSEService {
private timeArr: NodeJS.Timeout[] = [];
// keepalive相关状态
private lastKeepaliveTime: number = 0; // 记录最近收到keepalive事件的时间
private hasReceivedKeepalive: boolean = false; // 标记是否收到过keepalive事件
// 页面刷新监听器相关
private beforeUnloadHandler: (() => void) | null = null;
private isPageRefreshing: boolean = false;
constructor(config: SSEServiceConfig, handlers: SSEHandlers = {}) {
this.config = config;
this.handlers = handlers;
this.setupPageRefreshListener();
}
// 初始化SSE连接
......@@ -81,7 +85,6 @@ export class SSEService {
// 监听keepalive事件
this.eventSource.addEventListener('keepalive', (event) => {
this.lastKeepaliveTime = Date.now();
this.hasReceivedKeepalive = true; // 标记已收到keepalive
console.log('💓 收到keepalive事件,连接正常');
});
......@@ -89,6 +92,12 @@ export class SSEService {
this.eventSource.onerror = (error) => {
console.error('SSE error:', error);
// 检查是否为页面刷新导致的错误
if (this.isPageRefreshing) {
console.log('💡 页面刷新中,忽略SSE错误');
return; // 页面刷新时忽略所有错误
}
// 检查是否为"No activity"错误 - 使用更宽松的检测条件
const errorString = String(error).toLowerCase();
......@@ -117,8 +126,8 @@ export class SSEService {
this.closeSSE();
// 添加错误重连逻辑
if (!this.isReconnecting.value) {
// 添加错误重连逻辑(仅在非页面刷新状态下)
if (!this.isReconnecting.value && !this.isPageRefreshing) {
setTimeout(() => {
if (dialogSessionId) {
this.reconnectSSE(dialogSessionId);
......@@ -194,6 +203,36 @@ export class SSEService {
clearTimeout(item);
});
this.timeArr = [];
this.removePageRefreshListener();
}
// 设置页面刷新监听器
private setupPageRefreshListener(): void {
if (typeof window !== 'undefined') {
// 监听页面卸载事件
this.beforeUnloadHandler = () => {
this.isPageRefreshing = true;
console.log('💡 检测到页面刷新,主动关闭SSE连接');
this.closeSSE();
};
// 添加多个事件监听器,确保能捕获各种页面关闭场景
window.addEventListener('beforeunload', this.beforeUnloadHandler);
}
}
// 移除页面刷新监听器
private removePageRefreshListener(): void {
if (typeof window !== 'undefined') {
if (this.beforeUnloadHandler) {
window.removeEventListener('beforeunload', this.beforeUnloadHandler);
this.beforeUnloadHandler = null;
}
}
}
// 检查是否正在页面刷新
public getIsPageRefreshing(): boolean {
return this.isPageRefreshing;
}
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment