// defines: // variable ws (the websocket) // variable wsReady (boolean) // variable wsVerbose (boolean) // wsSend(msg) (send a message when websocket is ready) // wsOnMessage(function) (react to messages) sclass HInitWebSocket { S wsVar = "ws"; S onOpen; S readyMsg = "WebSocket ready!"; bool handleEvals = true; S headStuff aka get() { ret hreconnectingWebSockets() + hscript([[ var wsReady = false; var wsInitialMsgs = []; var wsMsgListeners = []; var wsVerbose = false; var wsURL = ((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + window.location.pathname + window.location.search; var ]] + wsVar + [[ = new ReconnectingWebSocket(wsURL); ]] + wsVar + [[.onopen = function(event) { wsReady = true; console.log(]] + jsQuote(readyMsg + " ") + [[+ wsURL); ws.onmessage = function(event) { wsMsgListeners.forEach(function(listener) { listener(event); }); }; wsInitialMsgs.forEach(function(msg) { if (wsVerbose) console.log("Sending initial msg: " + msg); ws.send(msg); }); wsInitialMsgs = []; ]] + jsDropTrailingComments(onOpen) + [[ }; ]] + wsVar + [[.onmessage = function(event) { ]] + unnull(onMessage) + [[ }; // send it now if ws is open already or when ws was opened function wsSend(msg) { if (wsReady) { wsInitialMsgs.push(msg); if (wsVerbose) console.log("Sending initial msg: " + msg); ws.send(msg); } } function wsOnMessage(f) { wsMsgListeners.push(f); } ]] + (!handleEvals ? "" : "wsOnMessage(" + js_evalOnWebSocketMessage() + ");\n") ); } }