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

Krishna picture Krishna · Dec 19, 2014 · Viewed 25k times · Source

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'));
               }               
         }
    }
}();

Answer

Michael Thompson picture Michael Thompson · Apr 28, 2015

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.