发布到Web worker时firefox中的DataCloneError(DataCloneError in firefox when posting to web worker)

我正在开发一个名为Ozai的帮助程序库,以使Web工作者更容易,但我遇到了firefox中的问题。 我从URL Blob创建一个Web worker并尝试将此有效负载发布到它:

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

使用此代码:

worker.postMessage(msg)

但它会引发DataCloneError异常 。 看起来Firefox的结构化克隆实现在一个非常简单的对象上失败了。 代码在Chrome和Safari上运行没有问题,但在最新版本的Firefox中失败。 我在这里错过了什么吗? 我该如何解决这个问题(最好不要对有效载荷进行字符串化)?

这是一个小提琴: http //jsfiddle.net/V8aCy/6/

还有一张Firelord Ozai的照片:

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:

最满意答案

您正在尝试使用具有引用arguments的属性的对象调用postMessage 。 这不起作用,因为数据必须是可转移的 ,这意味着完全是JSON可序列化的或实现Transferable (例如ArrayBuffer),哪些arguments不是。

使用Array.prototype.slice.call(arguments, 0)将arguments转换为数组,如果内容正常,可以对其进行序列化(克隆)。

纠正了小提琴 。

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.

更多推荐