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.
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 ;)