---
date: 2025-04-01T08:21:58.074Z
tags:
  - event
---

structuredClone 接口是用来结构化克隆 js 对象。
它需要 chrome 98+/safari 15.4+/firefox 94+开始支持。

之前只知道 messageChannel 的 postMessage 可以克隆对象，但它基于消息，是异步的。
今天我发现 history.replaceState 可以用来做 structuredClone 的代替，它是同步的！

> 当然 history.pushState 也是可以，但是它毕竟是 push，使用 replaceState 对 history 的影响更少。

```ts
const structuredClone =
  globalThis.structuredClone ??
  (<T>(data: T): T => {
    const oldState = history.state;
    history.replaceState(data, "");
    const clonedState = history.state;
    history.replaceState(oldState, "");
    return cloneState as T;
  });
```
