How to add a callback to ipc renderer send

时间:2017-07-17 15:28:49

标签: electron

Googling says you can add a callback to it, but the documentation just says "arg1, arg2, arg3" etc.

They also have sendSync, but I'd prefer not to block while my event is being sent [we're trying to do as much work through the browser as possible, because writing client code in node, seems a little daft].

If the creators have a sendSync, then surely they have a version with callbacks, or better yet promises.

Some examples of things i'd like to be able to do:

//callback
ipcRenderer.send('anaction', '[1, 2, 3]', function() { console.log('done anaction') });
//promise
ipcRenderer.send('anaction', '[1, 2, 3]')
    .then(function() { console.log('done anaction') });

//sync exists, but it blocks. I'm looking for a non-blocking function
ipcRenderer.sendSync('anacount', '[1, 2, 3]')
console.log('done anaction');

2 个答案:

答案 0 :(得分:13)

万一有人在2020年仍在寻找这个问题的答案,处理从主线程返回到渲染器的更好方法是根本不使用send,而是使用{{ 3}}和ipcMain.handle,它们使用async / await并返回Promises:

main.js

import { ipcMain } from 'electron';

ipcMain.handle('an-action', async (event, arg) => {
    // do stuff
    await awaitableProcess();
    return "foo";
}

renderer.js

import { ipcRenderer } from 'electron';

(async () => {
    const result = await ipcRenderer.invoke('an-action', [1, 2, 3]);
    console.log(result); // prints "foo"
})();

ipcMain.handleipcRenderer.invokeipcRenderer.invoke兼容,允许您公开一个API来向主线程询问渲染器线程中的数据,并在返回时对其进行处理。

main.js

import { ipcMain, BrowserWindow } from 'electron';

ipcMain.handle('an-action', async (event, arg) => {
    // do stuff
    await awaitableProcess();
    return "foo";
}

new BrowserWindow({
    ...
    webPreferences: {
        contextIsolation: true,
        preload: "preload.js" // MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY if you're using webpack
    }
    ...
});

preload.js

import { ipcRenderer, contextBridge } from 'electron';

// Adds an object 'api' to the global window object:
contextBridge.exposeInMainWorld('api', {
    doAction: async (arg) => {
        return await ipcRenderer.invoke('an-action', arg);
    }
});

renderer.js

(async () => {
    const response = await window.api.doAction([1,2,3]);
    console.log(response); // we now have the response from the main thread without exposing
                           // ipcRenderer, leaving the app less vulnerable to attack    
})();

答案 1 :(得分:8)

感谢unseen_damage提供此建议。 https://github.com/electron/electron/blob/master/docs/api/ipc-main.md#sending-messages

// In main process.
const {ipcMain} = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
    if(arg === 'ping')
        event.sender.send('asynchronous-reply', 'pong');
    else
        event.sender.send('asynchronous-reply', 'unrecognized arg');
})

// In renderer process (web page).
const {ipcRenderer} = require('electron')
function callAgent(args) {
    return new Promise(resolve => {
        ipcRenderer.send('asynchronous-message', args)
        ipcRenderer.on('asynchronous-reply', (event, result) => {
            resolve(result);
        })
    });
}