refactor: improve ws code

This commit is contained in:
草鞋没号
2021-11-09 08:59:37 +08:00
parent d3567065e8
commit a96991ac38
4 changed files with 55 additions and 45 deletions

View File

@@ -1,6 +1,7 @@
import fs from 'fs'
import { contextBridge, ipcRenderer } from 'electron'
import { domReady, injectWsCode } from './utils'
import { domReady } from './utils'
import { injectWsCode } from './ws'
import { useLoading } from './loading'
const isDev = process.env.NODE_ENV === 'development'
@@ -9,7 +10,7 @@ const { removeLoading, appendLoading } = useLoading()
domReady().then(() => {
appendLoading()
isDev && injectWsCode({
host: '127.0.0.1',
host: process.env.HOST, // '127.0.0.1'
port: process.env.PORT_WS as string, // process.env.npm_package_env_PORT_WS
})
})

View File

@@ -13,37 +13,3 @@ export function domReady(condition: DocumentReadyState[] = ['complete', 'interac
}
})
}
/** 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)
}
}
}

37
src/preload/ws.ts Normal file
View File

@@ -0,0 +1,37 @@
/**
* Ws client side
*/
/** Inject ws client-side 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)
}
}
}