Search code examples
javascriptweb-worker

Passing objects to a web worker


I'm trying to pass an object to a web worker through the postMessage function.
This object is a square that has a couple of functions to draw himself on a canvas and some other things. The web worker must return an array of this objects.
The problem is that when I call the postMessage function with this object, I get an this error:

Uncaught Error: DATA_CLONE_ERR: DOM Exception 25

I get this both sending the object to the worker and the other way around.
I think the error is because javascript must serialize the object, but can't do it because the object has functions built-in.

Does anyone ever had a similar problem? Do you know some workarround to this?
Thanks in advance.


Solution

  • There are a few reasons why the error that you mention could have been thrown, the reasons are listed here.

    When sending objects to web workers, the object is serialized, and later deserialized in the web worker if the object is a serializable object.

    This means that the methods for the objects you send to your web worker are not something that can be passed to the web worker (causing the error that you have run into), and you will need to provide the necessary methods/functions to the objects on the web worker's side of the environment, and make sure they are not part of the object that is passed to the web worker(s).