16

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'));
               }               
         }
    }
}();
Krishna
  • 161
  • 1
  • 1
  • 4
  • 1
    What is the type of "message" that is trying to be posted when the error occurs? Blob or File maybe? – Kevin Heidt Jan 22 '15 at 22:10
  • 1
    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. – Patrick Dark Apr 18 '18 at 09:12

1 Answers1

14

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.

Michael Thompson
  • 4,181
  • 1
  • 29
  • 24
  • 4
    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. – Scuzzy May 11 '17 at 23:43