const sec = window.location.protocol.startsWith("https"); const hostname = `${window.location.host}/ws/watch-together`; class WsConn { Running: Record; Handlers: Record any>; conn: WebSocket; onclose: () => void; constructor() { this.Running = {}; this.Handlers = {}; this.conn = new WebSocket(`ws${sec ? "s" : ""}://${hostname}`); this.setup(); } setup() { this.conn.onmessage = (data) => { const obj = JSON.parse(data.data); if (!this.Handlers[obj.event]) return; this.Running[obj.event] = true; this.Handlers[obj.event]?.(document.querySelector(obj.target), obj.value); setTimeout(() => (this.Running[obj.event] = false), 300); }; this.conn.onopen = () => { this.conn.send(JSON.stringify({target: "#myVideo", event: "tell"})); }; this.conn.onclose = () => { this.onclose?.(); this.conn = new WebSocket(`ws${sec ? "s" : ""}://${hostname}`); this.setup(); }; } RegisterAction(event: string, action: (obj: any, val: any) => any) { this.Handlers[event] = action; } EventHandler(valGetter: () => any) { return (event: Event) => { if (this.Running[event.type]) return; const ev = JSON.stringify({ target: getSelector(event.target as HTMLElement), event: event.type, value: valGetter.call(event.target), }); console.log(`Sending: ${ev}`); this.conn.send(ev); }; } }