Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 685
dgiulian Avatar asked Oct 09 '11 14:10

dgiulian


People also ask

Can I pass function to web worker?

You pass any function to the plugin as an argument and get result in callback. You also can "outsource" object's methods, function with dependecies, anonymous function and lambda. Enjoy.

How do I send a message to a web worker?

You need to use the postMessage() method in the onmessage event handler in worker. js : // src/worker. js onmessage = e => { const message = e.

What are the limitations of web workers?

Limitations Of Web WorkersA worker can't directly manipulate the DOM and has limited access to methods and properties of the window object. A worker can not be run directly from the filesystem. It can only be run via a server.

How can you send data using a worker object?

How can you send data using a Worker object? Explanation: Once you have a Worker object, you can send data to it with postMessage(). The value you pass to postMessage() will be cloned, and the resulting copy will be delivered to the worker via a message event.


1 Answers

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).

like image 170
erikvold Avatar answered Sep 20 '22 02:09

erikvold