fix: websocket disconnect when window focus

This commit is contained in:
GyDi 2023-08-05 17:21:15 +08:00
parent 54e491d8bf
commit 6f5acee1c3
No known key found for this signature in database
GPG Key ID: 9C3AD40F1F99880A
2 changed files with 9 additions and 2 deletions

View File

@ -8,10 +8,17 @@ export const useVisibility = () => {
setVisible(document.visibilityState === "visible");
};
const handleFocus = () => setVisible(true);
const handleClick = () => setVisible(true);
handleVisibilityChange();
document.addEventListener("focus", handleFocus);
document.addEventListener("pointerdown", handleClick);
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
document.removeEventListener("focus", handleFocus);
document.removeEventListener("pointerdown", handleClick);
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, []);

View File

@ -2,12 +2,12 @@ import { useRef } from "react";
export type WsMsgFn = (event: MessageEvent<any>) => void;
interface Options {
export interface WsOptions {
errorCount?: number; // default is 5
retryInterval?: number; // default is 2500
}
export const useWebsocket = (onMessage: WsMsgFn, options?: Options) => {
export const useWebsocket = (onMessage: WsMsgFn, options?: WsOptions) => {
const wsRef = useRef<WebSocket | null>(null);
const timerRef = useRef<any>(null);