# Local Font Access API

> window.queryLocalFonts() 在 local-fonts 权限之后以 FontData 对象列出设备上安装的字体。可指定查询选项、读取 FontData 成员、处理异常，并在失败时回退。

`window.queryLocalFonts()` 枚举用户设备上安装的字体。它返回的 Promise 在 `local-fonts` 权限获得授予后兑现，得到 `FontData` 数组。设计工具可以用这些数据按用户的本地字体排版。每个 `FontData` 提供 PostScript 名、全名、家族名和样式名，调用 `blob()` 还能取得原始 SFNT 字节。

只有桌面 Chromium 支持，起始版本是 Chrome 103 和采用同版内核的 Edge 与 Opera。Android 上的 Chrome、Firefox、Safari 的任何版本都没有实现（BCD `api.Window.queryLocalFonts`）；该方法带 `[SecureContext]`，在 `localhost` 以外的 `http://` 源上同样不存在。

## 语法

```js
window.queryLocalFonts()
window.queryLocalFonts(options)

fontData.blob()
```

`queryLocalFonts()` 返回 `Promise<sequence<FontData>>`，按 `postscriptName` 升序排列。`blob()` 返回 `Promise<Blob>`，其 `type` 为 `application/octet-stream`。规范允许浏览器只返回部分已安装字体。如果浏览器显示选择器，结果还会按用户的选择筛选。

## 参数

`queryLocalFonts()` 接受可选参数 `options`，类型为 `QueryOptions` 字典，字典内只有一项成员。

| 成员 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `postscriptNames` | `sequence<DOMString>` | 否 | 只返回 PostScript 名在列表内的字体，例如 `["Verdana-Bold", "Arial"]`。空列表什么都不返回；不传该成员则返回全部可选字体。匹配是精确的，带空格的 `"Verdana Bold"` 不会匹配任何字体。 |

返回的每个 `FontData` 提供四项只读 `USVString` 属性及一项方法。

| 成员 | 类型 | 说明 |
|---|---|---|
| `postscriptName` | `USVString` | PostScript 名，如 `"Arial-Bold"`；也是结果的排序键。 |
| `fullName` | `USVString` | 家族名加子家族名，如 `"Arial Bold"`。 |
| `family` | `USVString` | CSS `font-family` 使用的家族名，如 `"Arial"`。 |
| `style` | `USVString` | 子家族或样式名，如 `"Regular"`、`"Bold Italic"`。 |
| `blob()` | `Promise<Blob>` | 字体文件字节（SFNT 容器：TrueType、OpenType、WOFF 或 WOFF2）。 |

名称以单个字符串返回，取自字体 `name` 表中的美式英语版本或用户语言版本。需要其他语言时，要自行从 `blob()` 解析 `name` 表。

## 异常

`queryLocalFonts()` 以下列 `DOMException` 名称拒绝，顺序即规范的检查顺序。

| 异常 | 条件 |
|---|---|
| `SecurityError` | 文档的源是 opaque origin（例如没有 `allow-same-origin` 的沙箱 iframe）；或文档不允许使用 `local-fonts` 这一受策略控制的特性（默认允许列表为 `'self'`）；或调用时没有瞬时用户激活。 |
| `NotAllowedError` | 用户拒绝了 `local-fonts` 权限提示。 |

`blob()` 没有定义任何拒绝情形。Chromium 还会因规范未列出的情况拒绝调用。枚举后端缺失时以 `NotSupportedError` 和 `Not yet supported on this platform.` 拒绝，标签页隐藏时以 `SecurityError` 和 `Page needs to be visible.` 拒绝。它还会返回 `DataError` 和消息 `Font data exceeds memory limit.`，其他后端失败则返回 `UnknownError`（用户拒绝权限时 Chromium 也另有处理，见下方提示框）。

:::caution
Chromium 的 [`font_access.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/font_access/font_access.cc)（chromium.googlesource.com） 在枚举后端报告需要用户激活时（显示权限提示之前需要激活），以 `SecurityError: User activation is required.` 拒绝 `queryLocalFonts()`，Permissions Policy 拦截该功能时抛出 `SecurityError: Access to the feature "local-fonts" is disallowed by Permissions Policy`。权限提示在「This site would like to:」标题下列出 `Use the fonts on your computer so you can create high-fidelity content`（[`permissions_strings.grdp`](https://chromium.googlesource.com/chromium/src/+/main/components/permissions_strings.grdp)（chromium.googlesource.com），英文语言环境）。[Local Font Access 规范](https://wicg.github.io/local-font-access/)规定权限被拒绝时以 `NotAllowedError` 拒绝 Promise。Chromium 的 `font_access.cc` 则把 Promise 兑现为空数组（`// Return an empty font list if user has denied the permission request.`），所以仅凭返回的数组无法区分「用户拒绝授权」与「设备上没有可选字体」。页面可以通过 Permissions API 读取权限状态（`local-fonts` 权限，见 [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Local_Font_Access_API)）。
:::

## 示例

先检查 `window` 上有没有 `queryLocalFonts`，再从 `click` 处理函数中调用。API 缺失或用户拒绝时，使用页面自带的字体。

### 用设备字体填充字体选择器，并带一份内置回退列表

回退列表就是页面已经加载的 Web 字体，这样在 Firefox、Safari 或移动端 Chrome 中选择器也不会为空。Chrome 在用户拒绝时返回空数组，因此空结果也使用这份回退列表。

```js
const BUNDLED = ['Inter', 'Source Serif 4', 'JetBrains Mono'];

async function listFontFamilies() {
  if (!('queryLocalFonts' in window)) return BUNDLED;

  try {
    const fonts = await window.queryLocalFonts();
    if (fonts.length === 0) return BUNDLED; // Chrome 中被拒绝，或没有可选字体
    return [...new Set(fonts.map((f) => f.family))];
  } catch (err) {
    if (err.name === 'SecurityError' || err.name === 'NotAllowedError') return BUNDLED;
    throw err;
  }
}

document.querySelector('#pick-fonts').addEventListener('click', async () => {
  const select = document.querySelector('#font-family');
  select.replaceChildren(...(await listFontFamilies()).map((name) => new Option(name)));
});
```

同一字体家族内，字重和样式不同就会产生独立的 `FontData`，因此需要按 `family` 去重。例如，`"Arial"`、`"Arial-Bold"`、`"Arial-Italic"`、`"Arial-BoldItalicMT"` 是共享家族名 `"Arial"` 的四个条目。

### 渲染文档前确认某个特定字体是否存在

`postscriptNames` 把提示和结果都收窄到你关心的字体。字体缺失时改用文档内嵌的 Web 字体渲染，并告知用户版面可能有差异。

```js
async function hasLocalFont(postscriptName) {
  if (!('queryLocalFonts' in window)) return false;
  try {
    const matches = await window.queryLocalFonts({ postscriptNames: [postscriptName] });
    return matches.length === 1;
  } catch {
    return false; // 没有手势、被策略拦截，或用户拒绝
  }
}

document.querySelector('#open-document').addEventListener('click', async () => {
  const useLocal = await hasLocalFont('Verdana-Bold');
  document.body.style.fontFamily = useLocal ? '"Verdana"' : '"Verdana Web", sans-serif';
  document.querySelector('#font-note').hidden = useLocal;
});
```

只有当你必须自己读取字形轮廓或 `name` 表时（canvas 文本编辑器、字体检查器）才需要 `blob()`；CSS 按家族名引用已安装字体并不需要它。

## 另请参阅

- [File System Access API：读写本地文件](/zh/reference/capabilities/file-system-access/)，桌面 Chromium 另一项文件级能力，调用时也需要用户手势
- [字体与图片优化：font-display、picture 与 AVIF/WebP](/zh/reference/performance/fonts-images/)，Web 字体回退路径
- [桌面上的 PWA](/zh/reference/platforms/desktop/)
- [Local Font Access API: queryLocalFonts() method](https://wicg.github.io/local-font-access/#dom-window-querylocalfonts)（wicg.github.io）
- [Local Font Access API: local-fonts permission](https://wicg.github.io/local-font-access/#permissiondef-local-fonts)（wicg.github.io）
- [Window: queryLocalFonts() browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Window/queryLocalFonts#browser_compatibility)（developer.mozilla.org）