的消息被自动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
的一个包装。
他们可能使用HTML5结构化克隆,它比JSON更高效和灵活([在本答案中提到](http://stackoverflow.com/a/10916838/1114))。这样做可能会带来*微小*的性能提升,而不是手动JSON化。 –
考虑到API是在本地代码中实现的,它可能在V8中本地串行化。请注意,它与'JSON.stringify'序列化不同。 – Xan