Skip to content

Instantly share code, notes, and snippets.

@evertonfraga
Created June 24, 2025 15:36
Show Gist options
  • Save evertonfraga/b982a660733737d8eb9008a05d47477e to your computer and use it in GitHub Desktop.
Save evertonfraga/b982a660733737d8eb9008a05d47477e to your computer and use it in GitHub Desktop.
WebSocket connection management
class WebSocketManager {
constructor(url) {
this.url = url;
this.ws = null;
this.setupWebSocket();
this.setupCleanupEvents();
}
setupWebSocket() {
this.ws = new WebSocket(this.url);
// Optional: Handle connection events
this.ws.onopen = () => console.log('Connected');
this.ws.onclose = () => console.log('Disconnected');
}
setupCleanupEvents() {
// Handle page hide/unload
window.addEventListener('beforeunload', this.cleanup.bind(this));
window.addEventListener('unload', this.cleanup.bind(this));
// Handle tab visibility change
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
this.cleanup();
} else {
this.setupWebSocket(); // Reconnect when tab becomes visible
}
});
// Handle mobile events
document.addEventListener('pagehide', this.cleanup.bind(this));
document.addEventListener('freeze', this.cleanup.bind(this));
// Handle when browser minimizes or user switches apps
window.addEventListener('blur', this.cleanup.bind(this));
}
cleanup() {
if (this.ws) {
// Close code 1000 indicates normal closure
this.ws.close(1000, 'User navigated away');
this.ws = null;
}
}
// Method to manually close connection
disconnect() {
this.cleanup();
}
}
// Usage
const wsManager = new WebSocketManager('wss://your-websocket-server.com');
// To manually disconnect
// wsManager.disconnect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment