3

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

The chrome extension specification indicates that message passed between background and content script can be a Javascript object, which means that we can pass a Javascript object without using JSON.stringify. Does that mean Chrome internally execute JSON.stringify before sending messages? If not, is there a performance gain if I just pass Javascript object without JSONification?

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
sawa
  • 1,930
  • 3
  • 24
  • 33
  • 2
    They probably use HTML5 Structured Cloning, which is more efficient and flexible than JSON ([mentioned in this answer](http://stackoverflow.com/a/10916838/1114)). There will probably be a *tiny* performance gain by doing this, instead of manually JSONifying. – Jeremy Jul 06 '16 at 22:40
  • 2
    Considering that the APIs are implemented in the native code, it's probably serialized natively in V8. Note that it's _different_ from `JSON.stringify` serialization. – Xan Jul 07 '16 at 09:02

1 Answers1

5

In Chrome 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.

The same applies to chrome.runtime.sendMessage and chrome.tabs.sendMessage which use Port-based messaging internally.

It means that only JSON-compatible portion of the object is passed: strings, numbers, booleans, null, and objects/arrays that consist of the listed types. Complex types are not supported and will be sent as an empty object {} e.g. DOM elements, Set, Map, class instances, functions, and so on.

To send an unsupported type, serialize/stringify it manually, for example if map = new Map():

  • {data: [...map]} when sending
  • new Map(request.data) when receiving

Hopefully, Chrome will be able to send more types directly one day, see https://crbug.com/248548.

In Firefox, the structured clone algorithm is used, which preserves many popular complex types like Date, RegExp, Blob, File, ArrayBuffer, Map, Set, and several others.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136