Electron IPC 主要渲染多个监听器 - 监听器参数必须是一个函数

问题描述 投票:0回答:1

我正在根据以下文档实现 Electron 的模式 3,它是主要渲染内容: https://www. Electronjs.org/docs/latest/tutorial/ipc#pattern-3-main-to-renderer

我收到以下错误:

我的代码:

main.js

autoUpdater.on('download-progress', (progress) => {
        if (progress && progress.percent) {
            updateWindow.webContents.send('sendProgress', Math.round(progress.percent));  // send update event to update.preload
        }
    })

    // Download finished
    autoUpdater.on('update-downloaded', () => {
        updateWindow.webContents.send('downloadComplete');
        setTimeout(() => {
            autoUpdater.quitAndInstall(true,true); // restarts the application and install the update after update has been downloaded
        }, 40000);   // TODO ======= change to 3000
    })

我在这里发送 2 条消息。 发送进度下载完成

预加载.js

我在预加载中声明了桥

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('bridge', {
        sendProgress: (progress) => {
            ipcRenderer.on('sendProgress', progress);
        },
        downloadComplete: () => {
            console.log('--IN download complete-- in preload.js');
            ipcRenderer.on('downloadComplete');
        }
    }
);

更新.html

<script>
            window.bridge.sendProgress((event, progress) => {
                const element = document.getElementById('update-progress');
                if (element) {
                    element.innerText = progress;
                }
            })

            window.bridge.downloadComplete((event) => {
                const messageEl = document.getElementById('message');
                if (messageEl) {
                    console.log('altering innerText');
                    messageEl.innerText = 'Installing Update';
                }

                const progressEl = document.getElementById('progress');
                progressEl.style.display = 'none';

                const restartEl = document.getElementById('restart');
                restartEl.style.display = 'block';
            })


        </script>

问题表明我的错误在于 update.html 文件的第二个侦听器,即位于

window.bridge.downloadComplete((event) => {

另外,当我刚刚实现 1 个侦听器时,它就起作用了,但是当我实现第二个侦听器时,它就返回了此错误。

electron ipc
1个回答
0
投票

在预加载脚本中声明回调变量时,需要将回调变量添加到箭头函数中。

Preload.js 应如下所示:

// Import the necessary Electron modules
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('bridge', {
        sendProgress: (callback) => ipcRenderer.on('sendProgress', callback),
        downloadComplete: (callback) => ipcRenderer.on('downloadComplete', callback)
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.