I'm trying to call
parent.postMessage(obj, 'whatever');
from within an iframe and I'm getting this error: Uncaught DOMException: Failed to execute 'postMessage' on 'Window': An object could not be cloned.
It turns out the object I passed had methods, which is why the error message said An object could not be cloned
.
In order to fix this, you can do the following:
obj = JSON.parse(JSON.stringify(obj));
parent.postMessage(obj, 'whatever');
Depending on the data you're trying to pass, a more surgical approach could be to use simpler data structures that are compatible with postMessage()
.
The following will throw the error since postMessage
can't serialize SetIterator
:
let s = new Set();
parent.postMessage({s: s.values()}, '*');
The following will work as expected since postMessage
can serialize Array
:
let s = new Set();
parent.postMessage({s: [...s]}, '*');
This approach works more in line with the intent of implicit serialization by postMessage()
. When you need more complex data structures or can't be bothered to get all surgical, the good ole JSON.stringify/parse
hammer works just fine ;)
If you have functions in the object (or in nested objects) that you post, then cloning will fail.
I had this problem in the context of messaging an object to a web worker. The solution was to in-place convert all functions to source code strings, post the modified object and a list of paths (each an array of keys) to the found functions, and then convert the strings back to functions. The approach of storing paths to functions separately is safe in the sense that no previously unexisting functions can be created.
Here is my implementation. Nested arrays and objects are handled. null
values are handled. Circular references are not handled and will result in RangeError: Maximum call stack size exceeded
.
function deepFunctionsToStrings(obj, functionPaths = [], path = []) {
for (let key in obj) {
path.push(key);
let value = obj[key];
if (typeof value === 'object' && value !== null) {
deepFunctionsToStrings(value, functionPaths, path)
} else if (typeof value === 'function') {
obj[key] = value.toString();
functionPaths.push([...path]);
}
path.pop();
}
return functionPaths;
}
function deepStringsToFunctions(obj, functionPaths) {
for (let functionPath of functionPaths) {
let finalKey = functionPath.pop();
let value = obj;
for (let key of functionPath) {
value = value[key];
}
value[finalKey] = eval(value[finalKey]);
}
}
To post the object:
let objFunctionPaths = deepFunctionsToStrings(obj);
worker.postMessage({
obj: obj,
objFunctionPaths: objFunctionPaths
});
deepStringsToFunctions(obj, objFunctionPaths);
To receive the object in the web worker:
onmessage = function (e) {
obj = e.data.obj;
deepStringsToFunctions(obj, e.data.objFunctionPaths);
}
window.postMessage
. For more information see my answer with solution and detailed explanation why it happans.