I have an electron app where the renderer process leverages webworker to do some calculations.
It is working ok, but now I would like to send messages from the main process directly to the webworker.
I tried to attach the electron
object to the global one in my index.html
by doing so:
<script>
const electron = require('electron');
</script>
And then I was thinking I could get it like this in my webworker:
const ipcRenderer = self.electron.ipcRenderer
But this is not working, any idea?
Regards
We discussed this in Slack, but for posterity:
Workers use a share-nothing model, so you can't define a variable in your page (even globally or attached to window
) and expect it to show up inside the Worker. You can only send items over postMessage
(or fetch them from the Worker in other ways, e.g. Ajax requests). However, the data sent over postMessage
must be able to be cloned. From Worker.postMessage():
This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references
and from 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.
Thus there's no way to "send" the electron
object into the Worker; one solution would be to require it using Electron's node integration, but that's not supported for reasons stated in #797. One potential way to support what you're wanting to do is to send the message from the main process to the render process, and then forward it on to the Worker