electron-vite-react/preload/utils.ts

50 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** docoment ready */
export function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
return new Promise(resolve => {
if (condition.includes(document.readyState)) {
resolve(true)
} else {
document.addEventListener('readystatechange', () => {
if (condition.includes(document.readyState)) {
resolve(true)
}
})
}
})
}
/** Inject ws related code */
export function injectWsCode(options: {
host: string
port: string | number
}) {
const oScript = document.createElement('script')
oScript.id = 'ws-preload-hot-reload'
oScript.innerHTML = `
${__ws_hot_reload_for_preload.toString()}
${__ws_hot_reload_for_preload.name}(${JSON.stringify(options)})
`
document.body.appendChild(oScript)
}
function __ws_hot_reload_for_preload(options: { host: string; port: string | number }) {
const ws = new WebSocket(`ws://${options.host}:${options.port}`)
ws.onmessage = function (ev) {
try {
console.log('[preload] ws.onmessage:', ev.data)
const data = JSON.parse(ev.data) // { "cmd": "string", data: "string|number" }
if (data.cmd === 'reload') {
setTimeout(() => window.location.reload(), 999)
}
} catch (error) {
console.warn(`ws.onmessage should be accept "JSON.string" formatted string.`)
console.error(error)
}
}
}