1

我是堆栈溢出的全新用户,这是我的第一个问题。

我一直在研究使 Electron 应用程序更安全的方法,并遇到了以下关于 contextBridge 和 preload.js 的讨论。 如果 contextIsolation = true,是否可以使用 ipcRenderer?

我在下面复制了感兴趣的代码。我的问题是关于 Main 进程何时将消息发送回 Renderer 进程。

  1. Main 进程通过 win.webContents.send("fromMain", responseObj); 将消息发送回 Renderer;

  2. 在 Renderer 进程中没有活动的侦听器(没有 ipcRenderer.on,因为它在 preload.js 中)。我们只有 window.api.receive() 但这不是一个监听器本身?

  3. 那么,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");
4

1 回答 1

1

我自己的答案

经过多次挠头,我意识到我的问题的答案可能很微不足道。

以下是我认为 Main 进程能够将消息发送回 Renderer 进程的方式(参考原始问题中的代码):

  1. Main 进程创建一个新的浏览器窗口并加载 preload.js 脚本。发送和接收 API 现在已准备好供渲染器进程使用。

  2. 在启动 Renderer 进程时,renderer.js 脚本只是第一次运行并执行 window.api.receive(),而不管主进程是否已发送消息。因此,执行 preload.js 中定义的接收函数,激活 ipcRenderer.on 监听器。

  3. 简而言之,ipcRenderer.on 总是从第一次加载 renderer.js 时开始监听。

总之,我在查看脚本时根本没有正确遵循代码执行流程。

于 2021-07-29T10:54:11.217 回答