var socket; init_websocket(); onmessage = ww_onmessage; function ww_onmessage(event) { socket.send_event(event.data[0], event.data[1]); } /* Websocket setup */ function init_websocket() { let _socket; _socket = new WebSocket('wss://' + self.location.hostname + '/scorch/ws'); _socket.send_event = ws_send_event; _socket.onopen = ws_onopen; _socket.onmessage = ws_onmessage; _socket.onclose = ws_onclose; _socket.onerror = ws_onerror; self.socket = _socket; } function ws_send_event(event_title, data) { data = JSON.stringify({'event': event_title, 'data': data}); if (this.readyState == 0) { console.log("Websocket not ready."); return; } //console.log("Sending `" + event_title + "` event with following data: " + JSON.stringify(data)); this.send(data); } function ws_onopen(event) { console.log('Websocket connected to server.'); } function ws_onmessage(event) { postMessage(event.data); } function ws_onclose(event) { console.log('Websocket lost connection to server.'); if (event.wasClean) { return; } // no need to reconnect console.log('Connection break was unclean. Attempting to reconnect...'); self.setTimeout(init_websocket, 3000); } function ws_onerror(event) { console.log("Websocket encountered an error."); }