You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron中ipcRenderer.invoke无法向渲染进程传递数据问题

问题解决:Electron渲染进程调用preload方法返回undefined

问题原因

preload脚本中暴露的supportStatus方法仅在ipcRenderer.invoke的回调里打印了状态值,但没有将结果返回出去,函数执行完毕后默认返回undefined,导致渲染进程调用时无法获取正确状态。

解决方案

修改preload.js中的supportStatus方法,让它返回异步调用的结果:

写法一:简洁的await返回

contextBridge.exposeInMainWorld(
    'tintacle', {
        async supportStatus() {
            const status = await ipcRenderer.invoke('supportStatusHandler');
            console.log(status); // 保留原有打印逻辑
            return status; // 关键:将状态值返回给调用方
        }
    }
)

写法二:在then回调中返回值

contextBridge.exposeInMainWorld(
    'tintacle', {
        async supportStatus() {
            return ipcRenderer.invoke('supportStatusHandler').then(status => {
                console.log(status);
                return status; // 关键:将状态值传递给上层Promise
            });
        }
    }
)

修改后,渲染进程调用window.tintacle.supportStatus().then(status => console.log(status))就能正确拿到主进程返回的online或offline状态。

额外优化提示

主进程中的microSipPromise只会执行一次,如果后续需要重复检查MicroSip的运行状态,建议将检查逻辑封装成函数,每次调用supportStatusHandler时重新执行检查:

// main.js
function checkMicroSipStatus() {
    return new Promise((resolve, reject) => {
        let findPath = spawn('powershell.exe', ['get-process microsip | select-object -ExpandProperty Path']);
        
        findPath.stdout.once('data',  (data) => {
            exePath = iconv.decode(data, '866');
            resolve('online');
        });

        findPath.stderr.once('data', (data) => {
            dialog.showMessageBox({message: 'Запустите MicroSip', type: 'warning', title: 'Warning!'});
            resolve('offline');
        });

        // 处理进程退出但未触发stdout/stderr的边界情况
        findPath.on('exit', (code) => {
            if (code !== 0) {
                resolve('offline');
            }
        });
    });
}

ipcMain.handle('supportStatusHandler', () => {
    return checkMicroSipStatus();
})

内容的提问来源于stack exchange,提问作者Mirikkingg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:50:23