chrome扩展内部是否使用JSON.stiringify将postMessage转移到后台页面?

时间:2016-07-06 22:37:49

标签: javascript json google-chrome google-chrome-extension

  

消息可以包含任何有效的JSON对象(null,boolean,number,string,array或object)

chrome扩展规范表明在后台和内容脚本之间传递的消息可以是Javascript对象,这意味着我们可以在不使用JSON.stringify的情况下传递Javascript对象。这是否意味着Chrome在发送邮件之前会在内部执行JSON.stringify?如果没有,如果我只是在没有JSONification的情况下传递Javascript对象,会有性能提升吗?

1 个答案:

答案 0 :(得分:4)

消息在Chrome的JavaScript填充层中自动进行JSON序列化(字面意思是使用JSON.stringify),与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);
    }
  };

N.B。 chrome.runtime.postMessage / sendMessage只是上面显示的PortImpl的包装器。