"DataCloneError: The object could not be cloned." in FireFox 34

37,194

postMessage sends messages using the structured clone algorithm in Firefox and because of that there are certain things you need to adjust prior to sending.

In your example it isn't obvious what message contains but one hack-y way around structured clone is to coerce a bit. Sending a URL via postMessage will throw an error:

someWindow.postMessage(window.location, '*');
// ERROR

But you can do this to work around it:

var windowLocation = '' + window.location;
someWindow.postMessage(windowLocation, '*');
// WORKS

There are better ways to handle this but for what you've provided this should at least allow consistent behavior.

Share:
37,194
Krishna
Author by

Krishna

Updated on May 25, 2020

Comments

  • Krishna
    Krishna almost 4 years

    Using given function to post message, but getting error "DataCloneError: The object could not be cloned." at Line "target['postMessage'](message, target_url.replace( /([^:]+://[^/]+).*/, '$1'));" in FireFox-34, same code is working fine on Chrome and older version of FireFox.

    var storage = function() {
        return {
               postMessage : function(message, target_url, target) {
               if (!target_url) { 
                  return; 
               }
               var target = target || parent;  // default to parent
               if (target['postMessage']) { 
                       // the browser supports window.postMessage, so call it with a targetOrigin
                       // set appropriately, based on the target_url parameter.
                       target['postMessage'](message, target_url.replace( /([^:]+:\/\/[^\/]+).*/, '$1'));
                   }               
             }
        }
    }();
    
    • Kevin Heidt
      Kevin Heidt over 9 years
      What is the type of "message" that is trying to be posted when the error occurs? Blob or File maybe?
    • Patrick Dark
      Patrick Dark about 6 years
      If the message variable being passed includes DOM node objects such as a DocumentFragment object, you'll need to convert it to a string using the XMLSerializer.prototype.serializeToString method before sending. You can use a DOMParser object or the Element.prototype.innerHTML, Element.prototype.insertAdjacentHTML, or Element.prototype.outerHTML methods to unserialize the object on the other end.
  • Scuzzy
    Scuzzy almost 7 years
    I stumbled upon this answer which lead me to the string conversion solving my problem, I'd suggest simply using window.location.href which is the value the "tostring" method would be referencing, thank you.