2016-07-06 66 views
2

消息可以包含任何有效的JSON对象(NULL,布尔型,数字,字符串,数组或对象)Chrome扩展内部使用JSON.stiringify将postMessage添加到背景页面吗?

铬扩展规范指示消息的背景和内容脚本之间传递可以是Javascript对象,这意味着我们可以在不使用JSON.stringify的情况下传递一个Javascript对象。这是否意味着Chrome在发送消息之前内部执行JSON.stringify?如果不是,如果我只是通过没有JSONification的Javascript对象,会有性能上的提升吗?

+2

他们可能使用HTML5结构化克隆,它比JSON更高效和灵活([在本答案中提到](http://stackoverflow.com/a/10916838/1114))。这样做可能会带来*微小*的性能提升,而不是手动JSON化。 –

+2

考虑到API是在本地代码中实现的,它可能在V8中本地串行化。请注意,它与'JSON.stringify'序列化不同。 – Xan

回答

4

的消息被自动JSON序列化(字面使用JSON.stringify)在Chrome的JavaScript垫片层与作为可在source code of messaging.js中可以看出延长交互:

PortImpl.prototype.postMessage = function(msg) { 
    if (!$Object.hasOwnProperty(ports, this.portId_)) 
     throw new Error(kPortClosedError); 

    // JSON.stringify doesn't support a root object which is undefined. 
    if (msg === undefined) 
     msg = null; 
    msg = $JSON.stringify(msg); 
    if (msg === undefined) { 
     // JSON.stringify can fail with unserializable objects. Log an error and 
     // drop the message. 
     // 
     // TODO(kalman/mpcomplete): it would be better to do the same validation 
     // here that we do for runtime.sendMessage (and variants), i.e. throw an 
     // schema validation Error, but just maintain the old behaviour until 
     // there's a good reason not to (http://crbug.com/263077). 
     console.error('Illegal argument to Port.postMessage'); 
     return; 
    } 
    messagingNatives.PostMessage(this.portId_, msg); 
    }; 

同上,用于JSON.parse:

// Called by native code when a message has been sent to the given port. 
    function dispatchOnMessage(msg, portId) { 
    var port = ports[portId]; 
    if (port) { 
     if (msg) 
     msg = $JSON.parse(msg); 
     port.onMessage.dispatch(msg, port); 
    } 
    }; 

NB chrome.runtime.postMessage/sendMessage只是上面显示的PortImpl的一个包装。

相关问题