webservice/static/js/websocket.mjs

78 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-01-07 16:18:49 +01:00
export class Websocket {
constructor() {//{{{
this.websocket = null
this.websocket_int_ping = null
this.websocket_int_reconnect = null
this.hooks = {
open: [],
message: [],
error: [],
close: [],
}
}//}}}
register(event, fn) {//{{{
this.hooks[event].push(fn)
}//}}}
start() {//{{{
this.connect()
//this.loop()
}//}}}
loop() {//{{{
setInterval(() => {
if (this.websocket === null) {
console.log("websocket loop connect")
this.connect()
}
}, 1000)
}//}}}
connect() {//{{{
const protocol = location.protocol;
const domain = location.hostname;
const port = location.port;
let wsProtocol = 'wss'
if (protocol == 'http:')
wsProtocol = 'ws'
const websocketURI = `${wsProtocol}://${domain}:${port}/_ws`
this.websocket = new WebSocket(websocketURI)
this.websocket.onopen = (evt) => this.open(evt)
this.websocket.onmessage = (evt) => this.message(evt)
this.websocket.onerror = (evt) => this.error(evt)
this.websocket.onclose = (evt) => this.close(evt)
}//}}}
open() {//{{{
this.hooks.open.forEach(fn=>fn())
// A ping interval to implement a rudimentary keep-alive.
}//}}}
close() {//{{{
this.websocket = null
this.hooks.close.forEach(fn=>fn())
}//}}}
error(evt) {//{{{
this.websocket = null;
this.hooks.error.forEach(fn=>fn(evt))
}//}}}
message(evt) {//{{{
const msg = JSON.parse(evt.data)
if (msg.ID == '' && msg.Op == 'css_reload')
this.refreshCSS()
this.hooks.message.forEach(fn=>fn(evt.data))
return
}//}}}
refreshCSS() {//{{{
let links = document.getElementsByTagName('link')
Array.from(links).forEach(l=>{
if (l.rel == 'stylesheet' && !l.hasAttribute('x-no-reload')) {
l.href = l.href.replace(/\?.*/, '') + `?cache=${Date.now()}`
console.log(l.href)
}
})
}//}}}
}