# file_handlers 清单成员

> file_handlers 把已安装的 PWA 注册为操作系统中指定 MIME 类型与扩展名的打开程序，随后由 window.launchQueue 把被打开的文件交给页面处理。

清单成员 `file_handlers` 让已安装的 PWA 注册为指定 MIME 类型和扩展名的打开程序，取值是处理器对象数组。
用户在 Finder、资源管理器或"文件"应用中打开匹配文件时，系统用处理器的 `action` URL 启动应用，
页面再从 `window.launchQueue` 读取文件。这个成员只建立关联，页面仍需用 JavaScript 处理文件。

Chrome 102 与 Edge 102 在 Windows、macOS、Linux 与 ChromeOS 上处理该成员（BCD
`manifests.webapp.file_handlers`）。Android 版 Chrome、Safari 27、Firefox 157 与 Samsung Internet
会丢弃它，因此 PWA 的文件关联只存在于桌面 Chromium。

## 成员

| 属性 | 值 |
|---|---|
| 类型 | 对象数组。每个对象包含 `action`（字符串 URL）、`accept`（把 MIME 类型映射到扩展名数组的对象）、可选的 `icons`（操作系统为该类型文件显示的图像资源数组）以及可选的 `launch_type`（`"single-client"` 或 `"multiple-clients"`）。 |
| 默认值 | 不注册。成员缺失，或用户在系统层面移除了关联时，打开文件不会启动应用。 |
| 示例值 | `[{ "action": "/open", "accept": { "text/markdown": [".md"] } }]`。 |

Chromium 逐个校验处理器。`action` 必须是清单 `scope` 内的 URL；`action` 越界或无法解析时，Chromium 会
丢弃处理器，解析器消息为 `FileHandler ignored. Property 'action' is invalid.`；`accept` 里没有任何有效的
MIME 类型到扩展名映射时，消息为 `FileHandler ignored. Property 'accept' is invalid.`
（Chromium `manifest_parser.cc`）。个别映射或扩展名有问题只会被跳过并各自报一条消息，处理器的其余部分保留。
扩展名必须以点开头。清单之所以两者都要给，是因为各平台的注册方式不同：Linux 同时使用 MIME 类型和扩展名，
Windows 只用扩展名、忽略 MIME 类型（Manifest Incubations）。所以 `text/markdown` 配
`[".md", ".markdown"]` 声明了两个后缀。

`launch_type` 默认为 `"single-client"`：一次打开多个文件时，它们作为一个 `LaunchParams` 交给同一个
窗口，`files` 里有多个条目。设为 `"multiple-clients"` 时，每个文件各自启动一次，`files` 只含一个句柄。
Windows 不区分这两种设置，无论如何都按文件逐个启动应用（developer.chrome.com，"Handle files in
Progressive Web Apps"）。

首次通过处理器打开文件时，Chromium 会在页面拿到文件之前弹出权限对话框。对该站点的允许或阻止会持久保存；
清单更新改动 `file_handlers` 时，Chromium 会重置授权，忽略提示三次则会被拦截（developer.chrome.com）。在 Windows 与
macOS 上，这个关联要和原生应用争夺同一扩展名，用户可能仍需从"打开方式"菜单中选择该 PWA。

:::caution
Chrome 的[文件处理文档](https://developer.chrome.com/docs/capabilities/web-apis/file-handling)说明，注册为文件处理器的文本编辑器安装后，用户可以在 macOS 上右键点击 `.txt` 文件，选择 **Get Info**，把该应用设为默认打开程序。在 [`manifest_parser.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/manifest/manifest_parser.cc) 中，`action` 不是清单作用域内有效 URL 的处理器会被丢弃，并给出 `FileHandler ignored. Property 'action' is invalid.`；DevTools 的 [`AppManifestView.ts`](https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/panels/application/AppManifestView.ts) 在 **Errors and warnings** 下显示解析器的错误列表。
:::

## 示例

两份示例清单注册了 Markdown 编辑器，配套脚本接收文件句柄，并处理没有文件传入的情况。

### 为两个扩展名注册 Markdown 编辑器

一个处理器同时认领 `.md` 与 `.markdown`，把每次启动都路由到 `/editor`，并提供一个操作系统可
显示在该类型文件上的图标。`scope` 显式写出，以确保 `action` URL 明确位于其内。

```json
{
  "name": "Draft",
  "start_url": "/",
  "scope": "/",
  "display": "standalone",
  "file_handlers": [
    {
      "action": "/editor",
      "accept": {
        "text/markdown": [".md", ".markdown"],
        "text/plain": [".txt"]
      },
      "icons": [{ "src": "/icons/markdown-file.png", "sizes": "256x256", "type": "image/png" }],
      "launch_type": "single-client"
    }
  ]
}
```

在 Chrome 102+ 上安装后，操作系统会把 Draft 列为 `.md`、`.markdown` 与 `.txt` 的打开程序。忽略
该成员的浏览器会直接跳过它，应用能否安装与 `file_handlers` 无关。

### 消费启动参数并回退到文件选择器

`/editor` 页面在加载时设置 `launchQueue` 消费者。消费者设置之前到达的启动请求会留在队列里，
消费者就位后逐个送达（developer.chrome.com）。`launchQueue` 不存在时（桌面 Chromium 之外的任何浏览器），
把同一个函数接到一个打开 `<input type="file">` 的按钮上。

```js
async function openHandle(handle) {
  const file = await handle.getFile();
  editor.value = await file.text();
  document.title = `${file.name} - Draft`;
}

if ('launchQueue' in window) {
  window.launchQueue.setConsumer(async (launchParams) => {
    if (!launchParams.files.length) return; // 从图标启动，而不是从文件启动。
    for (const handle of launchParams.files) await openHandle(handle);
  });
} else {
  // 这里不可能发生文件处理启动，改为提供选择器。
  openButton.hidden = false;
  openButton.addEventListener('click', () => picker.click());
  picker.addEventListener('change', async () => {
    const [file] = picker.files;
    if (file) editor.value = await file.text();
  });
}
```

`launchParams.files` 中是 `FileSystemFileHandle` 对象，同一个句柄之后可以传给 `createWritable()`
直接写回原文件，无需保存对话框；`<input type="file">` 回退得到的是普通 `File` 对象，无法写回。

### 从操作系统侧核对注册

`launchQueue` 和 `LaunchParams` 只负责交付启动，不会报告系统关联是否存在。安装后到操作系统里核对：Windows 上在文件资源管理器
右键匹配文件，在 **Open with** 下找该应用；macOS 在 Finder 中
选中匹配文件，用 **File > Get Info > Open with** 查看。若应用不在列表里，去 DevTools > Application >
Manifest 看 `Errors and warnings` 里有没有关于该处理器的一行。

```json
{
  "file_handlers": [
    {
      "action": "https://other.example/open",
      "accept": { "text/markdown": [".md"] }
    }
  ]
}
```

`action` 指向的源与清单 `scope` 不同，Chromium 会丢弃这个处理器；控制台显示
`Manifest: FileHandler ignored. Property 'action' is invalid.`，操作系统不会注册这个类型。

## 另请参阅

- [处理文件](/zh/guides/file-handling/)
- [File System Access API：读写本地文件](/zh/reference/capabilities/file-system-access/)
- [launch_handler 清单成员](/zh/reference/manifest/launch-handler/)
- [scope 清单成员](/zh/reference/manifest/scope/)
- [Manifest Incubations: file_handlers member](https://wicg.github.io/manifest-incubations/#file_handlers-member)（wicg.github.io）
- [Let installed web applications be file handlers](https://developer.chrome.com/docs/capabilities/web-apis/file-handling)（developer.chrome.com）
- [Handle files in Progressive Web Apps](https://learn.microsoft.com/en-us/microsoft-edge/progressive-web-apps-chromium/how-to/handle-files)（learn.microsoft.com）