129

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.

1

3 Answers 3

216

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');
8
  • 13
    That's good to know, because Mozilla says messages are serialized for you: developer.mozilla.org/en-US/docs/Web/API/Window/postMessage Makes sense it wouldn't know how to serialize a function...
    – jonobr1
    Commented Apr 7, 2017 at 21:19
  • 5
    were you able to access methods on that object after passing to parent?? Commented Jul 30, 2018 at 9:45
  • 2
    Note that doing so you'll crash on cyclics (which should be preserved by postMessage) instead of on functions.
    – Kaiido
    Commented Sep 5, 2018 at 7:45
  • 1
    In my case the problem were caused by an nonexistent variable passed in parameters. Commented Oct 2, 2018 at 8: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
    Commented Nov 15, 2018 at 21:19
0

Depending on the data you're trying to pass, a more surgical approach could be to use simpler data structures that are compatible with postMessage().

The following will throw the error since postMessage can't serialize SetIterator:

let s = new Set();
parent.postMessage({s: s.values()}, '*');

The following will work as expected since postMessage can serialize Array:

let s = new Set();
parent.postMessage({s: [...s]}, '*');

This approach works more in line with the intent of implicit serialization by postMessage(). When you need more complex data structures or can't be bothered to get all surgical, the good ole JSON.stringify/parse hammer works just fine ;)

0

If you have functions in the object (or in nested objects) that you post, then cloning will fail.

I had this problem in the context of messaging an object to a web worker. The solution was to in-place convert all functions to source code strings, post the modified object and a list of paths (each an array of keys) to the found functions, and then convert the strings back to functions. The approach of storing paths to functions separately is safe in the sense that no previously unexisting functions can be created.

Here is my implementation. Nested arrays and objects are handled. null values are handled. Circular references are not handled and will result in RangeError: Maximum call stack size exceeded.

function deepFunctionsToStrings(obj, functionPaths = [], path = []) {
    for (let key in obj) {
        path.push(key);
        let value = obj[key];
        if (typeof value === 'object' && value !== null) {
            deepFunctionsToStrings(value, functionPaths, path)
        } else if (typeof value === 'function') {
            obj[key] = value.toString();
            functionPaths.push([...path]);
        }
        path.pop();
    }
    return functionPaths;
}

function deepStringsToFunctions(obj, functionPaths) {
    for (let functionPath of functionPaths) {
        let finalKey = functionPath.pop();
        let value = obj;
        for (let key of functionPath) {
            value = value[key];
        }
        value[finalKey] = eval(value[finalKey]);
    }
}

To post the object:

let objFunctionPaths = deepFunctionsToStrings(obj);
worker.postMessage({
    obj: obj,
    objFunctionPaths: objFunctionPaths
});
deepStringsToFunctions(obj, objFunctionPaths);

To receive the object in the web worker:

onmessage = function (e) {
    obj = e.data.obj;
    deepStringsToFunctions(obj, e.data.objFunctionPaths);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.