htmgo/framework/assets/js/htmxextensions/livereload.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-09-17 17:13:22 +00:00
import htmx from "htmx.org";
import {createWebSocketClient} from "../util/ws";
let lastVersion = "";
htmx.defineExtension("livereload", {
init: function () {
const host = window.location.host;
console.log('livereload extension initialized.');
createWebSocketClient({
url: `ws://${host}/dev/livereload`,
onOpen: () => {
},
onMessage: (message) => {
if(lastVersion === "") {
lastVersion = message;
}
if(lastVersion !== message) {
2024-09-17 18:35:44 +00:00
lastVersion = message;
reload()
2024-09-17 17:13:22 +00:00
}
},
onError: (error) => {
},
onClose: () => {
}
})
},
// @ts-ignore
onEvent: function (name, evt) {
},
2024-09-17 18:35:44 +00:00
});
function reload() {
window.location.reload()
// fetch(window.location.href).then(response => {
// return response.text();
// }).then(html => {
// document.open();
// document.write(html);
// document.close();
// }).catch(err => {
// console.log('failed to fetch live reload', err)
// setTimeout(reload, 100)
// })
2024-09-17 18:35:44 +00:00
}