Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataCloneError in firefox when posting to web worker

I am working on a helper library called Ozai to make web workers easier, but am running in to a problem in firefox. I create a web worker from a URL Blob and attempt to post this payload to it:

msg = {
    "id":"0fae0ff8-bfd1-49ea-8139-3d03fb9584e4",
    "fn":"fn",
    "args":[100,200]
}

Using this code:

worker.postMessage(msg)

But it throws a DataCloneError exception. It looks like Firefox's implementation of structured cloning is failing on a very simple object. The code runs without problems on Chrome and Safari, but fails in the latest version of Firefox. Am I missing something here? How do I get around this (preferably without stringifying the payload)?

Here's a fiddle: http://jsfiddle.net/V8aCy/6/

And a pic of Firelord Ozai:

enter image description here

like image 553
mako-taco Avatar asked Oct 29 '13 15:10

mako-taco


People also ask

What methods can be used to stop web workers?

You can terminate web workers from the main thread immediately or from the worker thread. From the main thread, you can terminate a web worker by calling the terminate() method of the Web Workers API: worker.

How many web workers can run concurrently?

How many web workers can run concurrently JavaScript? A web worker is a JavaScript program running on a different thread, in parallel with main thread. The browser creates one thread per tab. The main thread can spawn an unlimited number of web workers, until the user's system resources are fully consumed.

Which of the following JavaScript type object are not accessible by web workers?

Workers do NOT have access to: The DOM (it's not thread-safe) The window object. The document object.


1 Answers

You're trying to call postMessage with an object that has a property referencing arguments. That doesn't work because data has to be transferable, which means either fully JSON-serializable or implementing Transferable (e.g. ArrayBuffer), which arguments is not.

Use Array.prototype.slice.call(arguments, 0) to convert arguments into an array, which can be serialized (cloned) if the contents are OK.

Corrected fiddle.

like image 114
nmaier Avatar answered Sep 30 '22 14:09

nmaier