无法在“ServiceWorker"上执行“postMessage":无法克隆函数 [英] Failed to execute 'postMessage' on 'ServiceWorker': function could not be cloned

查看:99
本文介绍了无法在“ServiceWorker"上执行“postMessage":无法克隆函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 Service Worker 实例发布消息.我收到以下错误:

I am trying to post a message to a service worker instance. I get the following error:

未能在ServiceWorker"上执行postMessage":function (){obj.removeListener(ev, fn);} 无法克隆.

Failed to execute 'postMessage' on 'ServiceWorker': function (){ obj.removeListener(ev, fn); } could not be cloned.

我的代码如下:

var socket = io();

function onYouTubeIframeAPIReady() {
    //Tell the service worker who I am
    navigator.serviceWorker.ready.then(serviceWorkerRegistration => {
        navigator.serviceWorker.controller.postMessage({
            name: 'socketInit',
            value: socket
        });
    });
}

知道为什么会这样吗?

推荐答案

实际上马上就找到了答案,它在文档中.您基本上不能拥有 Function 类型的属性(它可能在 io() 对象内部的某处),因为它不能被克隆:

Actually found the answer right away, it's in the docs. You basically can't have a Function-type property (which probably is there somewhere inside the io() object) because it can't be cloned:

参数
message要发送给 Service Worker 的消息.这可以是任何结构化可克隆类型.

Parameters
message The message to send to the service worker. This can be any structured-clonable type.

一个structured-clonable-type被定义为:

结构化克隆算法是由 HTML5 定义的算法复制复杂 JavaScript 对象的规范.它被使用在内部通过以下方式与 Workers 之间传输数据时postMessage().它通过递归输入来构建一个克隆对象,同时维护之前访问过的引用的映射以避免无限遍历循环.

The structured clone algorithm is an algorithm defined by the HTML5 specification for copying complex JavaScript objects. It is used internally when transferring data to and from Workers via postMessage(). It builds up a clone by recursing through the input object while maintaining a map of previously visited references in order to avoid infinitely traversing cycles.

结构化克隆不适用的事情

ErrorFunction 对象不能被结构化克隆算法复制;尝试这样做会抛出一个DATA_CLONE_ERR 异常.尝试克隆 DOM 节点同样会抛出 DATA_CLONE_ERR 异常.对象的某些参数是不保留:不保留 RegExp 对象的 lastIndex 字段.属性描述符、setter 和 getter(以及类似的类似元数据的功能)不会重复.例如,如果一个对象使用属性描述符标记为只读,它将是可读写的在副本中,因为这是默认条件.原型链不会被遍历和复制.

Error and Function objects cannot be duplicated by the structured clone algorithm; attempting to do so will throw a DATA_CLONE_ERR exception. Attempting to clone DOM nodes will likewise throw a DATA_CLONE_ERR exception. Certain parameters of objects are not preserved: The lastIndex field of RegExp objects is not preserved. Property descriptors, setters, and getters (as well as similar metadata-like features) are not duplicated. For example, if an object is marked read-only using a property descriptor, it will be read-write in the duplicate, since that's the default condition. The prototype chain does not get walked and duplicated.

这篇关于无法在“ServiceWorker"上执行“postMessage":无法克隆函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆