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:
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 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.
Workers do NOT have access to: The DOM (it's not thread-safe) The window object. The document object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With