Electron:如何将 message/data 从预加载传递到渲染器?
Electron: How to pass the message/data from preload to renderer?
基本上我希望渲染器不断地监听来自的消息,并且预加载可以随时将消息发送到渲染器。基本上我的场景是:
- 每当用户将任何内容复制到剪贴板时,主进程都会通过 webContents.send("clipboard-updated");
将消息发送到预加载
- 主进程会将新接收到的剪辑保存到数据库中。
- Preload 会在收到来自 main 的消息后将消息发送给渲染器。
- Render 将再次从数据库中获取数据并刷新 UI。
这是整个场景,在这里我无法弄清楚如何将消息发送到渲染器以便它可以刷新 UI.
您可以使用 Window.postMessage()
将数据从预加载发送到渲染器
// preload
window.postMessage("your-data", "*");
// renderer
window.addEventListener("message", (event) => {
// event.source === window means the message is coming from the preload
// script, as opposed to from an <iframe> or other source.
if (event.source === window) {
console.log("from preload:", event.data);
}
});
或者您可以直接从主进程与渲染器进程通信,即所谓的“主世界”here in the docs
基本上我希望渲染器不断地监听来自的消息,并且预加载可以随时将消息发送到渲染器。基本上我的场景是:
- 每当用户将任何内容复制到剪贴板时,主进程都会通过 webContents.send("clipboard-updated"); 将消息发送到预加载
- 主进程会将新接收到的剪辑保存到数据库中。
- Preload 会在收到来自 main 的消息后将消息发送给渲染器。
- Render 将再次从数据库中获取数据并刷新 UI。 这是整个场景,在这里我无法弄清楚如何将消息发送到渲染器以便它可以刷新 UI.
您可以使用 Window.postMessage()
将数据从预加载发送到渲染器
// preload
window.postMessage("your-data", "*");
// renderer
window.addEventListener("message", (event) => {
// event.source === window means the message is coming from the preload
// script, as opposed to from an <iframe> or other source.
if (event.source === window) {
console.log("from preload:", event.data);
}
});
或者您可以直接从主进程与渲染器进程通信,即所谓的“主世界”here in the docs