var socket; function load() { socket = init_websocket(); } /* Websocket setup */ function init_websocket() { let socket = new WebSocket('wss://' + window.location.hostname + ws_uri); socket.send_event = send_event; socket.onmessage = onmessage; socket.onclose = onclose; socket.onerror = onerror; socket.events = {}; return socket; } function send_event(event_title, data) { data = JSON.stringify({'event': event_title, 'data': data}); if (socket.readyState == 0) { console.log("Socket is still opening!"); return; } socket.send(data); } function onmessage(e) { console.log(e); } function onclose(e) { if (e.wasClean) { return; } // no need to reconnect console.log(e); console.log('Websocket lost connection to server. Re-trying...'); //socket = init_websocket(); //await sleep(5000); } function onerror(e) { console.log("Websocket error!") console.log(e); }