javascriptweb-worker

Post function to webworker


How is it possible to send a (copy of) function from my main thread to my worker?

Whenever I try: worker.postMessage({data, func: (data) => data), firefox gives me an error message: DataCloneError: The object could not be cloned.

As for Chrome, the message differ, but the error still occur: Uncaught DOMException: Failed to execute 'postMessage' on 'Worker': An object could not be cloned.


Solution

  • Not tested this yet, but it seems that from the spec, only objects that can be send to a Worker are "Transferable" objects: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects

    I found some examples, in the first one the process is not detailled, but i'm guessing he uses a kind or URL encode, for an object, it can be converted to JSON like in the second example.

    How to pass functions to JavaScript Web Worker

    Passing objects to a web worker

    I have to do this too in a couple of days, i can keep updated with what i have that will be tested..