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?
Seems platform specific. If you run in Firefox you get a more descriptive error:
So
structuredClone
in a browser needs to be executed in thewindow
context. In a browser you can have multiple windows (iframes) acting as a global context opposed to Node where you have only one. SostructuredClone
should know which window to act upon.To solve the problem you could bind the function: