【问题标题】:Electron: How to pass the message/data from preload to renderer?Electron:如何将消息/数据从预加载传递到渲染器?
【发布时间】:2021-08-12 15:06:13
【问题描述】:

基本上我希望渲染器不断监听来自的消息,并且预加载可以随时将消息发送到渲染器。基本上我的情况是:

  1. 每当用户将任何内容复制到剪贴板时,主进程都会通过 webContents.send("clipboard-updated"); 将消息发送到预加载;
  2. 主进程会将新收到的剪辑保存到数据库中。
  3. Preload 会在收到来自 main 的消息后将消息发送给渲染器。
  4. Render 将再次从数据库中获取数据并刷新 UI。 这是整个场景,在这里我无法弄清楚如何将消息发送到渲染器以便它可以刷新 UI。

【问题讨论】:

标签: javascript user-interface electron


【解决方案1】:

您可以使用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所示

【讨论】:

    猜你喜欢
    • 2022-06-17
    • 2020-10-18
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2020-08-03
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多