// defines: // variable ws (the websocket) // variable wsReady (boolean) // variable wsVerbose (boolean) // wsSend(msg) (send a message when websocket is ready) // wsOnMessage(function(event) {...}) (react to messages) // wsOnOpen(function() {}) (react to opening of websocket) sclass HInitWebSocket { S wsVar = "ws"; S readyMsg = "WebSocket ready!"; bool handleEvals = true; // automatically handle {"eval":"jsCode();"} S headStuff aka get() { ret hreconnectingWebSockets() + hscript(js()); } LS dependencies() { ret ll(hjssnippet(hreconnectingWebSockets_snippetID(), "data-comment" := "ReconnectingWebSocket")); } S js() { ret formatDollarVars([[ var wsReady = false; var wsInitialMsgs = []; var wsMsgListeners = []; var wsOpenListeners = []; var wsVerbose = $wsVerbose; 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); wsOpenListeners.forEach(function(f) { f(); }); 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 = []; }; // 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 wsOnOpen(f) { wsOpenListeners.push(f); } function wsOnMessage(f) { wsMsgListeners.push(f); } ]], +wsVerbose) + (!handleEvals ? "" : "wsOnMessage(" + js_evalOnWebSocketMessage() + ");\n"; } }