問題描述
谷歌上說你可以給它添加一個回調,但文檔只是說arg1、arg2、arg3"等等.
Googling says you can add a callback to it, but the documentation just says "arg1, arg2, arg3" etc.
他們也有 sendSync,但我不希望在發送我的事件時阻止 [我們試圖通過瀏覽器做盡可能多的工作,因為在節點中編寫客戶端代碼似乎有點愚蠢].
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].
如果創建者有一個 sendSync,那么他們肯定有一個帶有回調的版本,或者更好的承諾.
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');
推薦答案
如果有人在 2020 年仍在尋找這個問題的答案,處理從主線程回復到渲染器的更好方法是不要使用send
,而是使用 ipcMain.handle
和 ipcRenderer.invoke
,利用async
/await
并返回Promises:
In case anybody is still looking for an answer to this question in 2020, a better way to handle replying from the main thread back to the renderer is not to use send
at all, but rather to use ipcMain.handle
and ipcRenderer.invoke
, which make use of async
/await
and return Promises:
ma??in.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.handle
和 ipcRenderer.invoke
與 contextBridge
,允許您公開一個 API 以向主線程請求來自渲染器線程的數據,并在它返回后對其進行處理.
ipcMain.handle
and ipcRenderer.invoke
are compatible with contextBridge
, allowing you to expose an API to ask the main thread for data from the renderer thread and do something with it once it comes back.
ma??in.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
})();
這篇關于如何向 ipc 渲染器發送添加回調的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!