在 webworker 中使用 ipcRenderer?
Use ipcRenderer in a webworker?
我有一个 Electron 应用程序,其中渲染器进程利用 webworker 进行一些计算。
它工作正常,但现在我想从主进程直接向 webworker 发送消息。
我试图通过这样做将 electron
对象附加到我的 index.html
中的全局对象:
<script>
const electron = require('electron');
</script>
然后我想我可以在我的 webworker 中得到它:
const ipcRenderer = self.electron.ipcRenderer
但这行不通,知道吗?
此致
我们在 Slack 中讨论过这个问题,但为了后代:
Worker 使用无共享模型,因此您不能在页面中定义变量(即使是全局变量或附加到 window
)并期望它显示在 Worker 中。您只能通过 postMessage
发送项目(或以其他方式从 Worker 获取它们,例如 Ajax 请求)。但是,通过 postMessage
发送的数据必须能够被克隆。来自 Worker.postMessage():
This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references
来自The structured clone algorithm:
Property descriptors, setters, and getters (as well as similar metadata-like features) are not duplicated. For example, if an object is marked read-only using a property descriptor, it will be read-write in the duplicate, since that's the default condition.
The prototype chain does not get walked and duplicated.
因此无法将 "send" 对象 electron
放入 Worker 中;一种解决方案是要求它使用 Electron 的节点集成,但由于 #797 中所述的原因,该解决方案不受支持。支持您想要做的事情的一种可能方法是将消息从主进程发送到渲染进程,然后将其转发给 Worker
我有一个 Electron 应用程序,其中渲染器进程利用 webworker 进行一些计算。
它工作正常,但现在我想从主进程直接向 webworker 发送消息。
我试图通过这样做将 electron
对象附加到我的 index.html
中的全局对象:
<script>
const electron = require('electron');
</script>
然后我想我可以在我的 webworker 中得到它:
const ipcRenderer = self.electron.ipcRenderer
但这行不通,知道吗?
此致
我们在 Slack 中讨论过这个问题,但为了后代:
Worker 使用无共享模型,因此您不能在页面中定义变量(即使是全局变量或附加到 window
)并期望它显示在 Worker 中。您只能通过 postMessage
发送项目(或以其他方式从 Worker 获取它们,例如 Ajax 请求)。但是,通过 postMessage
发送的数据必须能够被克隆。来自 Worker.postMessage():
This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references
来自The structured clone algorithm:
Property descriptors, setters, and getters (as well as similar metadata-like features) are not duplicated. For example, if an object is marked read-only using a property descriptor, it will be read-write in the duplicate, since that's the default condition. The prototype chain does not get walked and duplicated.
因此无法将 "send" 对象 electron
放入 Worker 中;一种解决方案是要求它使用 Electron 的节点集成,但由于 #797 中所述的原因,该解决方案不受支持。支持您想要做的事情的一种可能方法是将消息从主进程发送到渲染进程,然后将其转发给 Worker