Skip to content

Commit

Permalink
fix: port onmessage
Browse files Browse the repository at this point in the history
  • Loading branch information
toyobayashi committed Mar 6, 2024
1 parent f925649 commit dc63b2e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
10 changes: 7 additions & 3 deletions app/src/ts/renderer-back.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import './renderer/preload'
import { ipcRenderer } from 'electron'
import DB from './common/db'
import { batchDownload, batchStop, getBatchErrorList, setDownloaderProxy } from './renderer/back/batch-download'
// import mainWindowId from './renderer/back/main-window-id'
Expand All @@ -8,11 +7,16 @@ import readMaster from './renderer/back/on-master-read'
let manifest: DB | null = null
let master: DB | null = null

ipcRenderer.on('port', e => {
window.node.electron.ipcRenderer.on('port', e => {
const mainWindowPort = e.ports[0]
const portEvent = new window.node.events.EventEmitter()

mainWindowPort.onmessage = function (event) {
portEvent.emit('message', event)
}

function defineRemoteFunction (name: string, fn: (...args: any[]) => any): void {
mainWindowPort.addEventListener('message', (event) => {
portEvent.on('message', (event) => {
if (event.data.type === name) {
Promise.resolve(fn(...event.data.payload)).then(ret => {
mainWindowPort.postMessage({
Expand Down
11 changes: 6 additions & 5 deletions app/src/ts/renderer/ipc-back.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,17 @@ function createChannelName (): string {
}

let backWindowPort: MessagePort
const backWindowPortEvent = new window.node.events.EventEmitter()

ipcRenderer.on('port', e => {
backWindowPort = e.ports[0]

backWindowPort.addEventListener('message', (ev) => {
backWindowPort.onmessage = function (ev) {
if (ev.data.type === 'setBatchStatus') {
store.commit(Action.SET_BATCH_STATUS, ev.data.payload[0])
}
})
backWindowPortEvent.emit('message', ev)
}
})

function invokeBackWindow<T> (name: string, args: any[] = []): Promise<T> {
Expand All @@ -31,16 +33,15 @@ function invokeBackWindow<T> (name: string, args: any[] = []): Promise<T> {
return
}
const callbackChannel = createChannelName()
backWindowPort.addEventListener('message', (ev) => {
console.log('recieve: ', ev.data)
backWindowPortEvent.once('message', (ev) => {
if (ev.data.id === callbackChannel) {
if (ev.data.err) {
reject(new Error(ev.data.err))
} else {
resolve(ev.data.data)
}
}
}, { once: true })
})
backWindowPort.postMessage({
id: callbackChannel,
type: name,
Expand Down

0 comments on commit dc63b2e

Please sign in to comment.