Failed to execute ‘postMessage’ on ‘Window’ GoogleTagManager

This happens all the time, if something can not be duplicated by the structured clone algorithm. This algorithm is used by window.postMessage. If we read the documentation from window.postMessage for the first parameter:

message
Data to be sent to the other window. The data is serialized using the structured clone algorithm.

and then open the description from structured clone algorithm (see last link above) then we can read:

The structured clone algorithm is an algorithm defined by the HTML5 specification for copying complex JavaScript objects. It is used internally when transferring data to and from Workers via postMessage() or when storing objects with IndexedDB. It builds up a clone by recursing through the input object while maintaining a map of previously visited references in order to avoid infinitely traversing cycles.

Things that don’t work with structured clone

  • Error and Function objects cannot be duplicated by the structured clone algorithm; attempting to do so will throw a
    DATA_CLONE_ERR exception.

  • Attempting to clone DOM nodes will likewise throw a DATA_CLONE_ERR exception.

  • Certain parameters of objects are not preserved:

    • The lastIndex field of RegExp objects is not preserved.
    • Property descriptors, setters, and getters (as well as similar metadata-like features) are not duplicated. For example, if an object
      is marked read-only using a property descriptor, it will be read-write
      in the duplicate, since that’s the default condition.
    • The prototype chain does not get walked and duplicated.

Supported types

  • All primitive types (Note: However not symbols)
  • Boolean object
  • String object
  • Date
  • RegExp (Note: The lastIndex field is not preserved.)
  • Blob
  • File
  • FileList
  • ArrayBuffer
  • ArrayBufferView (Note: This basically means all typed arrays like Int32Array etc.)
  • ImageData
  • Array
  • Object (Note: This just includes plain objects (e.g. from object literals))
  • Map
  • Set

I tested it with some objects and I can show you following examples when this is happening…

Error-Example with custom function

var obj = {something: function(){}};
window.postMessage(obj, '*'); // DataCloneError

Error-Example with native function

var obj = {something: window.alert};
window.postMessage(obj, '*'); // DataCloneError

The same we will see with native functions like Boolean, Date, String, RegExp, Number, Array.

Error-Example with native object

var obj = {something: document};
window.postMessage(obj, '*'); // DataCloneError

Error-Example with HTML element object

var obj = {something: document.createElement('b')};
window.postMessage(obj, '*'); // DataCloneError

We could write more examples if we read the description from The structured clone algorithm above, but I think here it is enough.

What we could do to avoid this error

In our code we could use only supported types (see the list above) in our objects. But in not our code we have to contact the developers from this code and write them how they have to correct their code. In the case from the Google Tag Manager you could write it to the Official Google Tag Manager Forum with description how they have to correct their code.

Workaround for some browsers

In some browsers you can not override native methods for security reasons. For example IE does not allow to override window.postMessage. But other browsers like Chrome allow to override this method like follows:

var postMessageTemp = window.postMessage;
window.postMessage = function(message, targetOrigin, transfer)
{
    postMessageTemp(JSON.parse(JSON.stringify(message)), targetOrigin, transfer)
};

But note that window is a global object of JavaScript context and it is not created from the prototype. In other words: you can not override it with window.prototype.postMessage = ....

Example with workaround

var obj = {something: window};

var postMessageTemp = window.postMessage;
window.postMessage = function(message, targetOrigin, transfer)
{
    function cloneObject(obj)
    {
        var clone = {};
        for(var i in obj)
        {
            if(typeof(obj[i]) == 'object' && obj[i] != null)
            {
                if((''+obj[i]) == '[object Window]')
                {
                    delete obj[i];
                    continue;
                }

                clone[i] = cloneObject(obj[i]);
            }
            else
                clone[i] = obj[i];
        }
        return clone;
    }

    // to avoid weird error causing by window object by JSON.stringify() execution.
    var clone = cloneObject(message);

    postMessageTemp(JSON.parse(JSON.stringify(clone)), targetOrigin, transfer)
};

window.postMessage(obj, '*');

console.log('We do not have any errors.');

How to implement this workaround

Please put this overriden window.postMessage function in script part in your HTML page before Google Tag Manager script. But in better way you could help the developers from Google Tag Manager to understand and to correct this error and you can wait for corrected Google Tag Manager script.

Leave a Comment