的消息被自動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