I found a great solution on this page: sam-low.com
Once the original connection has been closed, you need to create a new WebSocket object with new event listeners
function startWebsocket() {
var ws = new WebSocket('ws://localhost:8080')
ws.onmessage = function(e){
console.log('websocket message event:', e)
}
ws.onclose = function(){
// connection closed, discard old websocket and create a new one in 5s
ws = null
setTimeout(startWebsocket, 5000)
}
}
startWebsocket();
Note that if there’s a problem reconnecting, the new WebSocket object will still receive another close event, meaning that onclose()
will be executed even if it never technically opened. That’s why the delay of five seconds is sensible - without it you could find yourself creating and destroying thousands of websocket connections at a rate that would probably break something.