# Navigation API

> window.navigation 把单页应用路由收拢到一处：navigate()、navigate 事件与 intercept()、它会抛出的异常，以及 History API 回退方案。

`window.navigation` 是 HTML 标准提供的路由和会话历史接口，可以替代 `history.pushState()` 路由方案。几乎每次导航都会触发 `navigate`（地址栏输入的跨文档加载和 `javascript:` URL 除外），调用 `event.intercept()` 就能接管导航，由你的处理函数在同一文档内渲染。`navigation.entries()` 返回会话历史，每项都有稳定的 key；调用 `navigation.traverseTo(key)` 即可退回指定项，无需计算 `history.go()` 的偏移量。

Chrome 102 在桌面与 Android 上发布了 `Navigation`，Edge 102 跟进（BCD `api.Navigation`）；`intercept()` 方法在 Chrome 105 到来，取代了 Chrome 102 到 107 存在过的 `transitionWhile()`。Firefox 147 与 macOS、iOS 上的 Safari 26.2 同时发布了 `Navigation`、`NavigateEvent` 和 `intercept()`。Chrome 的 `navigate()` 仍接受 `javascript:` URL，与规范相悖（[Chromium bug 439994590](https://crbug.com/439994590)）。

## 语法

```js
navigation.navigate(url)
navigation.navigate(url, options)
navigation.reload()
navigation.reload(options)
navigation.traverseTo(key)
navigation.traverseTo(key, options)
navigation.back()
navigation.back(options)
navigation.forward()
navigation.forward(options)
navigation.updateCurrentEntry(options)

navigation.addEventListener("navigate", (event) => {
  event.intercept(options);
});
```

`navigate()`、`reload()`、`traverseTo()`、`back()` 和 `forward()` 返回普通对象 `NavigationResult`，其中有 `committed` 和 `finished` 两个 Promise，兑现值都是目标 `NavigationHistoryEntry`。

同文档导航由 `intercept()` 接管后，URL 和 `navigation.currentEntry` 更新时 `committed` 兑现；所有处理函数的 Promise 都兑现后，`finished` 才兑现；只要任一处理函数的 Promise 拒绝，`finished` 就会拒绝。跨文档导航、状态码 204 或 205，以及带 `Content-Disposition: attachment` 标头的响应，都不会让这两个 Promise 完结。

`intercept()` 仅在 `navigate` 事件派发期间有效，返回 `undefined`。`updateCurrentEntry()` 同步返回 `undefined`。

## 参数

`navigate()` 接受一个按文档 base URL 解析的 `url` 字符串，外加可选的 `NavigationNavigateOptions` 字典。`reload()` 接受 `NavigationReloadOptions`，三个遍历方法接受 `NavigationOptions`，`updateCurrentEntry()` 接受 `NavigationUpdateCurrentEntryOptions`，其唯一成员 `state` 为必填。

| 成员 | 所属字典 | 类型 | 必填 | 说明 |
|---|---|---|---|---|
| `info` | `NavigationOptions`（除 `updateCurrentEntry()` 外的所有方法） | `any` | 否 | 原样交给随之触发的 `navigate` 事件的 `event.info`，之后丢弃；用来传 UI 提示，例如滑动方向。 |
| `state` | `NavigationNavigateOptions`、`NavigationReloadOptions`、`NavigationUpdateCurrentEntryOptions` | `any`，须可结构化序列化 | 否（`updateCurrentEntry()` 为必填） | 存到新条目上（`updateCurrentEntry()` 则更新当前条目的状态），用 `entry.getState()` 读回。导航最终跨文档时被忽略。 |
| `history` | `NavigationNavigateOptions` | `"auto"`、`"push"` 或 `"replace"` | 否，默认 `"auto"` | `"auto"` 推入新条目；目标 URL 与文档当前 URL 相同时改为替换，初始的 `about:blank` 文档上则一律替换。显式指定 `"push"` 时，URL 相同不受限制，只有在强制替换的场合（例如初始的 `about:blank` 文档）才抛 `NotSupportedError`。 |

`event.intercept()` 接受 `NavigationInterceptOptions` 字典。多次调用会追加处理函数；后传的 `focusReset` 或 `scroll` 覆盖先传的，Chrome 会在控制台打印一条警告。

| 成员 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `handler` | `() => Promise<undefined>` | 否 | URL 提交后运行。它的 Promise 决定 `finished`、`navigation` 上的 `navigatesuccess` 或 `navigateerror` 事件，以及 `navigation.transition`。 |
| `precommitHandler` | `(controller) => Promise<undefined>` | 否 | URL 变更前运行，可以调用 `controller.redirect(url)`；只有 `event.cancelable` 为 true 时允许。 |
| `focusReset` | `"after-transition"` 或 `"manual"` | 否 | 处理函数结束后焦点是否移到第一个 `autofocus` 元素（没有则移到 `<body>`）；导航期间焦点已被移动时跳过。 |
| `scroll` | `"after-transition"` 或 `"manual"` | 否 | 处理函数全部兑现后浏览器是否自动恢复（遍历）或重置（推入，回到顶部或滚到片段）滚动位置；选 `"manual"` 时在内容就绪后自行调用 `event.scroll()`。 |

路由可以读取 `NavigateEvent` 的这些属性来决定如何处理导航：`canIntercept`、`destination`（含 `url`、`key`、`index`、`sameDocument` 与 `getState()`）、`navigationType`（`"push"`、`"replace"`、`"reload"` 或 `"traverse"`）、`hashChange`、`downloadRequest`、`formData`、`userInitiated`、`signal` 与 `info`。`hasUAVisualTransition` 在 Chrome 118 加入，`sourceElement` 在 Chrome 135 加入（BCD `api.NavigateEvent`）。

## 异常

导航开始前就能判定的失败返回「early error result」，`committed` 和 `finished` 以同一个异常拒绝，通常是 `DOMException`。`updateCurrentEntry()`、`intercept()` 和 `scroll()` 则同步抛出异常。

| 异常 | 条件 |
|---|---|
| `SyntaxError` | `navigate()`：`url` 按文档 base URL 解析失败。 |
| `NotSupportedError` | `navigate()`：`url` 使用 `javascript:` 协议，或在强制替换的场合（初始的 `about:blank` 文档）指定了 `history: "push"`。 |
| `DataCloneError` | `navigate()`、`reload()`、`updateCurrentEntry()`：`state` 不可结构化序列化（函数、DOM 节点、`WeakMap`）。 |
| `InvalidStateError` | `navigate()` 与 `reload()`：文档不是 fully active 或正在卸载。`traverseTo()`：没有条目匹配该 key。`back()` 与 `forward()`：`currentEntry.index` 已是 0 或最后一个。`updateCurrentEntry()`：`currentEntry` 为 null。`intercept()`：派发结束后调用、`preventDefault()` 之后调用，在不可取消的事件上传了 `precommitHandler`，或文档不是 fully active。`scroll()`：提交前调用、调用第二次、`preventDefault()` 之后调用，或文档不是 fully active。 |
| `SecurityError` | `intercept()`：`canIntercept` 为 false（目标跨源，或导航无法转为同文档），或事件不是可信事件。 |
| `AbortError` | `finished`，URL 尚未提交时 `committed` 也会：导航被更新的导航取代、被用户停止加载，或被 `preventDefault()` 取消；`event.signal` 同一时刻触发 `abort`。 |

`handler()` 的 Promise 被拒绝时保留它自己的原因：`finished` 以该原因拒绝，`navigation` 带着它触发 `navigateerror`。这个原因本身也可以是 `DOMException`，比如通过 `event.signal` 取消 `fetch()` 得到的 `AbortError`。

:::caution
Chromium 的 [`navigate_event.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/core/navigation_api/navigate_event.cc)（chromium.googlesource.com） 与 [`navigation_api.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/core/navigation_api/navigation_api.cc)（chromium.googlesource.com） 定义了以下失败情形。对不可拦截的导航（例如跨源目标）调用 `event.intercept()`，抛出 `SecurityError: A navigation with URL 'https://other.example/' cannot be intercepted by in a window with origin 'https://app.example' and URL 'https://app.example/'.`（重复的「by in」原样来自源码）。在 `navigate` 事件分发结束后调用 `intercept()`，例如在监听器里 `await` 之后，抛出 `InvalidStateError: intercept() may only be called while the navigate event is being dispatched.`。没有更早的条目时调用 `navigation.back()`，`committed` 与 `finished` 两个 Promise 都以 `InvalidStateError: Cannot go back` 拒绝。
:::

## 示例

示例要求页面已有应用壳，并提供 `<main id="view">` 元素供各路由填充。

### 用单个 `navigate` 监听器渲染路由

一个监听器就能看到链接点击、表单提交、`navigation.navigate()` 调用以及前进后退遍历。路由不该接管的情况提前返回：跨源目标、仅片段变化、下载。`handler()` 运行时 URL 已经改变，所以先渲染占位，再把取回的内容换进去。

```js
navigation.addEventListener("navigate", (event) => {
  if (!event.canIntercept || event.hashChange || event.downloadRequest !== null) {
    return;
  }

  const url = new URL(event.destination.url);

  event.intercept({
    async handler() {
      const view = document.querySelector("#view");
      view.setAttribute("aria-busy", "true");
      const response = await fetch(`/fragments${url.pathname}`, { signal: event.signal });
      view.innerHTML = await response.text();
      view.removeAttribute("aria-busy");
    },
  });
});
```

把 `event.signal` 传给 `fetch()`。用户在请求完成前再次导航，就会取消旧请求，避免迟到的响应覆盖新路由。

### `intercept()` 缺失时回退到 History API

只检测 `window.navigation` 不足以判断实现可用：Chrome 102 到 104 暴露了 `navigation` 却没有 `intercept()`，为 `intercept()` 写的监听器在那里第一次点击就会抛 `TypeError`。检查原型上的方法，否则接上经典的 `click` 加 `popstate` 组合。

```js
const hasNavigationApi =
  "navigation" in window &&
  typeof NavigateEvent !== "undefined" &&
  typeof NavigateEvent.prototype.intercept === "function";

async function render(pathname) {
  const response = await fetch(`/fragments${pathname}`);
  document.querySelector("#view").innerHTML = await response.text();
}

if (hasNavigationApi) {
  navigation.addEventListener("navigate", (event) => {
    if (!event.canIntercept || event.hashChange || event.downloadRequest !== null) return;
    const { pathname } = new URL(event.destination.url);
    event.intercept({ handler: () => render(pathname) });
  });
} else {
  document.addEventListener("click", (event) => {
    const link = event.target.closest("a[href]");
    if (!link || link.origin !== location.origin || event.button !== 0 || event.metaKey || event.ctrlKey) return;
    event.preventDefault();
    history.pushState(null, "", link.href);
    render(link.pathname);
  });
  window.addEventListener("popstate", () => render(location.pathname));
}
```

回退方案中，表单提交、`location.assign()` 调用，以及落到另一个文档上的遍历都不会经过 `click` 监听器，而是加载文档（遍历时旧文档也可能从 bfcache 恢复）。

### 用 `traverseTo()` 和存储的 state 回到已知条目

`navigation.entries()` 返回当前 frame 中与当前条目连续的同源条目，各条目的 `key` 在重载后依然有效，向导式流程因此可以回到第一步而不必知道中间推入了几步。导航时把步骤存进 `state`，目标页就能恢复表单。

```js
const startKey = navigation.currentEntry.key;

async function goToStep(step) {
  const { finished } = navigation.navigate(`/checkout/${step}`, {
    state: { step, startedAt: Date.now() },
  });
  await finished;
}

function restart() {
  if (!navigation.entries().some((entry) => entry.key === startKey)) {
    navigation.navigate("/checkout/1", { history: "replace" });
    return;
  }
  navigation.traverseTo(startKey);
}

navigation.addEventListener("currententrychange", () => {
  const state = navigation.currentEntry.getState();
  if (state?.step) document.querySelector("#step").textContent = String(state.step);
});
```

`startKey` 若已不在 `entries()` 里（比如它和当前条目之间隔了一个跨源条目），`traverseTo()` 会以 `InvalidStateError` 拒绝；这时 `some()` 检查让 `restart()` 走替换分支。

## 另请参阅

- [View Transitions](/zh/reference/performance/view-transitions/)，给 `intercept()` 处理函数执行的 DOM 更新加动画
- [Back/forward cache（bfcache）](/zh/reference/performance/bfcache/)，决定跨文档遍历是否恢复旧文档
- [Speculation Rules API](/zh/reference/performance/speculation-rules/)，预取可能的下一个文档，适用于监听器交给浏览器处理的导航
- [HTML Standard: the navigation API](https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api)（html.spec.whatwg.org）
- [HTML Standard: navigate() method](https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-navigate)（html.spec.whatwg.org）
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)（developer.chrome.com）
- [WICG navigation-api explainer](https://github.com/WICG/navigation-api)（github.com）
- [Chromium bug 439994590: `javascript:` URLs accepted by navigate()](https://crbug.com/439994590)（crbug.com）