63

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.

nieve
  • 3,015
  • 2
  • 18
  • 24
  • This happens all the time, if something can not be duplicated by the structured clone algorithm. This algorithm is used by `window.postMessage`. For more information see my **[answer with solution and detailed explanation why it happans](https://stackoverflow.com/a/52223341)**. – Bharata Sep 28 '18 at 11:51

1 Answers1

112

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');
nieve
  • 3,015
  • 2
  • 18
  • 24
  • 7
    That's good to know, because Mozilla says messages are serialized for you: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage Makes sense it wouldn't know how to serialize a function... – jonobr1 Apr 07 '17 at 21:19
  • 2
    were you able to access methods on that object after passing to parent?? – Prakash Palnati Jul 30 '18 at 09:45
  • 1
    Note that doing so you'll crash on cyclics (which should be preserved by postMessage) instead of on functions. – Kaiido Sep 05 '18 at 07:45
  • 1
    In my case the problem were caused by an nonexistent variable passed in parameters. – Daniel Santana Oct 02 '18 at 08:46
  • When using AngularJS, I found this solution removed fields that were of TrustedValueHolderType. I'm looking for a solution for dealing with this. – PatS Nov 15 '18 at 21:19