我是堆栈溢出的全新用户,这是我的第一个问题。
我一直在研究使 Electron 应用程序更安全的方法,并遇到了以下关于 contextBridge 和 preload.js 的讨论。 如果 contextIsolation = true,是否可以使用 ipcRenderer?
我在下面复制了感兴趣的代码。我的问题是关于 Main 进程何时将消息发送回 Renderer 进程。
Main 进程通过 win.webContents.send("fromMain", responseObj); 将消息发送回 Renderer;
在 Renderer 进程中没有活动的侦听器(没有 ipcRenderer.on,因为它在 preload.js 中)。我们只有 window.api.receive() 但这不是一个监听器本身?
那么,window.api.receive() 是如何知道何时运行的呢?
编辑/已解决:请参阅下面发布的我自己的答案,谢谢。
main.js
ipcMain.on("toMain", (event, args) => {
fs.readFile("path/to/file", (error, data) => {
// Do something with file contents
// Send result back to renderer process
win.webContents.send("fromMain", responseObj);
});
});
preload.js
const {
contextBridge,
ipcRenderer
} = require("electron");
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);
渲染器.js
window.api.receive("fromMain", (data) => {
console.log(`Received ${data} from main process`);
});
window.api.send("toMain", "some data");