javascriptnode.jsbrowserstructured-clone

JavaScript structuredClone got `Illegal invocation` in Chrome/Edge, but not in NodeJS


Run the following code in a browser:

({ clone: structuredClone }).clone(1);

will got Uncaught TypeError: Illegal invocation, tested in Chrome/Edge.

However running the code in NodeJS is fine, tested in NodeJS v20.

Workaround:

({ clone: (v) => structuredClone(v) }).clone(1);

Or

({ clone: function(v) { return structuredClone(v)} }).clone(1);

Is this the expected behaviour?


Solution

  • Seems platform specific. If you run in Firefox you get a more descriptive error:

    Uncaught TypeError: 'structuredClone' called on an object that does not implement interface Window.
    

    So structuredClone in a browser needs to be executed in the window context. In a browser you can have multiple windows (iframes) acting as a global context opposed to Node where you have only one. So structuredClone should know which window to act upon.

    structuredClone.call(window, 1);
    
    // hmm, works with null too, seems takes the current window
    structuredClone.call(null, 1);
    
    structuredClone.call(1, 1);

    To solve the problem you could bind the function:

    ({ clone: structuredClone.bind(null) }).clone(1);