Does chrome extension internally use JSON.stiringify to postMessage over to background page?

后端 未结 1 2014
醉酒成梦
醉酒成梦 2020-12-20 01:44

A message can contain any valid JSON object (null, boolean, number, string, array, or object)

The chrome extension specification indicat

相关标签:
1条回答
  • 2020-12-20 02:30

    The messages are automatically JSON-serialized (literally using JSON.stringify) in Chrome's JavaScript shim layer that interacts with an extension as can be seen in the 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);
      };
    

    Ditto for 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 is just a wrapper over PortImpl shown above.

    0 讨论(0)
提交回复
热议问题