Electron - window.postMessage 在预加载和具有特定目标来源的渲染器之间进行对话

标签 electron

我想使用 targetOrigin 验证/区分消息的来源的 postMessage之间preload.jsrenderer.js启用上下文隔离。

因此,如果消息来自 preload.js , originTarget 类似于 file://preload.js ,以及来自渲染器 file://renderer.js .

设置 file://preload.jsfile://renderer.js , 报错 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('file://'). .

有人知道如何实现我想要实现的目标吗?
谢谢

最佳答案

报价 MDN web docs :

Lastly, posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future.


所以在 preload.js您需要使用 *targetOrigin :
window.addEventListener("DOMContentLoaded", () => {
  window.postMessage({ type: "fooType", text: "barMsg" }, "*")
})
在接收渲染器(网页)中,将消息处理限制为 file://计划和 window出于安全原因的对象引用:
window.addEventListener(
  "message",
  event => {
    if (event.origin === "file://" && event.source === window) {
      console.log(event.data)
    }
  },
  false
)
这也适用于更具限制性的配置,如下所示( webPreferences 用于 BrowserWindow ):
{
  nodeIntegration: false,
  contextIsolation: true,
  enableRemoteModule: false,
  preload: path.join(__dirname, "preload.js")
}

关于 Electron - window.postMessage 在预加载和具有特定目标来源的渲染器之间进行对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522354/

相关文章:

electron - 在 Electron 中使用 Elm 0.19 时无法读取未定义的属性 'Elm'

node.js - Pycharm 与 Electron - runnerw.exe : CreateProcess failed with error 193: %1 is not a valid Win32 application

javascript - Electron Packager - 使用相对路径

javascript - 返回后功能仍在运行

javascript - 子渲染器electronicjs中对 Node 的访问失败

node.js - 用于监控 Electron 应用的工具

javascript - 如何将 Electron ipcRenderer 集成到基于 TypeScript 的 Angular 2 应用程序中?

node.js - Electron 禁用CTRL + A键盘快捷键

javascript - Node 智能卡在扫描卡时抛出 SCardConnect 错误,断开连接后抛出 SCardListReaders 错误

node.js - 如何使用 react 前端点击 Electron 将文件下载到系统