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?
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 sendingnew Map(request.data) when receivingHopefully, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With