我有一个 Electron 应用程序,其中渲染器进程利用 webworker 进行一些计算。
它工作正常,但现在我想将消息从主进程直接发送到网络工作人员。
我尝试通过这样做将 Electron
对象附加到我的 index.html
中的全局对象:
<script>
const electron = require('electron');
</script>
然后我想我可以在我的网络 worker 中得到这样的结果:
const ipcRenderer = self.electron.ipcRenderer
但这不起作用,有什么想法吗?
问候
最佳答案
我们在 Slack 中讨论了这个问题,但为了后代:
Workers 使用无共享模型,因此您无法在页面中定义变量(即使是全局变量或附加到窗口
)并期望它显示在 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.
因此无法将 electron
对象“发送”到 Worker 中;一种解决方案是要求使用 Electron 的节点集成,但由于 #797 中所述的原因不支持该解决方案。 。支持您想要做的事情的一种潜在方法是将消息从主进程发送到渲染进程,然后将其转发到工作线程
关于web-worker - 在网络 worker 中使用 ipcRenderer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35671037/