fix: ws cleanup when page visibility change

This commit is contained in:
hamster1963 2025-01-09 11:33:03 +08:00
parent 4da870dd79
commit b1c5b6e0a8

View File

@ -106,15 +106,29 @@ export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({ url, child
useEffect(() => { useEffect(() => {
connect() connect()
// 添加页面可见性变化监听
const handleVisibilityChange = () => {
if (document.hidden) {
// 页面隐藏时断开连接
cleanup()
} else {
// 页面可见时重新连接
connect()
}
}
// 添加页面卸载事件监听 // 添加页面卸载事件监听
const handleBeforeUnload = () => { const handleBeforeUnload = () => {
cleanup() cleanup()
} }
window.addEventListener('beforeunload', handleBeforeUnload)
document.addEventListener("visibilitychange", handleVisibilityChange)
window.addEventListener("beforeunload", handleBeforeUnload)
return () => { return () => {
cleanup() cleanup()
window.removeEventListener('beforeunload', handleBeforeUnload) document.removeEventListener("visibilitychange", handleVisibilityChange)
window.removeEventListener("beforeunload", handleBeforeUnload)
} }
}, [url]) }, [url])