# FileSystemHandle

> FileSystemHandle represents a file or directory entry and exposes its kind, name, entry comparison, and permission methods.

The `FileSystemHandle` interface represents a file or directory entry. Its read-only `kind` and `name` properties describe the entry, while `isSameEntry()` tests whether another handle represents the same entry ([File System Standard](https://fs.spec.whatwg.org/#api-filesystemhandle)).

## Where it is supported

BCD `api.FileSystemHandle` records the core interface from Chrome 86, Chrome for Android 109, Firefox 111, and Safari 15.2; its mirrored records cover the related browsers. BCD separately records `api.FileSystemHandle.queryPermission` and `api.FileSystemHandle.requestPermission` from Chrome 86 and Chrome for Android 109, with no Firefox or Safari support. The interface is exposed to `Window` and workers in secure contexts and is serializable, as defined by the File System Standard.

## Syntax

```js
handle.kind
handle.name

await handle.isSameEntry(otherHandle)
await handle.queryPermission()
await handle.queryPermission({ mode: "readwrite" })
await handle.requestPermission()
await handle.requestPermission({ mode: "readwrite" })
```

The File System Standard defines `kind`, `name`, and `isSameEntry()`. The File System Access draft adds `queryPermission()` and `requestPermission()` as a partial interface. Code that accepts handles from different sources should detect those permission methods before calling them.

## Members

The core interface defines `kind`, `name`, and `isSameEntry()`. `FileSystemFileHandle` and `FileSystemDirectoryHandle` inherit these members; browser APIs usually return one of these derived handles to application code ([FileSystemHandle](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle), MDN).

| Member | Type | Description |
|---|---|---|
| `kind` | `"file" \| "directory"` | Reports whether the represented entry is a file or a directory. |
| `name` | `USVString` | Returns the represented entry's name. A name is not an identity: the standard permits multiple handles to share one locator, and different directories can contain entries with the same name. |
| `isSameEntry(other)` | `Promise<boolean>` | Resolves to `true` when both handles have the same file-system locator, and otherwise resolves to `false`. |

The File System Access draft adds the permission methods below for handles that participate in its local-file permission model.

| Member | Argument | Result | Description |
|---|---|---|---|
| `queryPermission(descriptor)` | Optional `{ mode: "read" \| "readwrite" }`; `mode` defaults to `"read"` | `Promise<"granted" \| "denied" \| "prompt">` | Returns the permission state without asking the user ([queryPermission()](https://wicg.github.io/file-system-access/#api-filesystemhandle-querypermission)). |
| `requestPermission(descriptor)` | Optional `{ mode: "read" \| "readwrite" }`; `mode` defaults to `"read"` | `Promise<"granted" \| "denied" \| "prompt">` | For `{ mode: "readwrite" }`, returns `"denied"` without running the permission request algorithm when read permission is `"denied"`, even if write permission is `"prompt"`. Otherwise, a non-`"prompt"` state is returned directly, while a `"prompt"` state runs the permission request algorithm ([requestPermission()](https://wicg.github.io/file-system-access/#api-filesystemhandle-requestpermission)). |

Handles can come from an origin-private file system through `navigator.storage.getDirectory()`, from a local picker, or from a drag item. The core members do not reveal which route produced a handle. The WICG draft states that entries in a bucket file system have permission state `"granted"`; its permission extension matters when a handle represents an entry outside that bucket.

`isSameEntry()` compares entries, not strings. Use it when a stored handle and a newly obtained handle might point to the same file. Comparing only `name` cannot establish that identity because the standard associates identity with the locator.

## Exceptions

The standard algorithm for `isSameEntry()` resolves its promise with a boolean. The permission extension has additional failure conditions when `requestPermission()` needs to turn a `"prompt"` state into a permission request.

| Operation | Failure |
|---|---|
| `requestPermission()` from a worker when the state is `"prompt"` | Rejects with `SecurityError` because the permission request algorithm requires a `Window`. |
| `requestPermission()` without transient user activation when the state is `"prompt"` | Rejects with `SecurityError`. Call it from a click or another activation-bearing action. |
| `requestPermission()` in a frame whose origin differs from the top-level origin when the state is `"prompt"` | Rejects with `SecurityError`. |
| An operation after the default read-permission query returns `"denied"` | The WICG draft says any operation on that handle rejects. A `{ mode: "readwrite" }` query reports write permission instead, so a denied result does not establish that read permission is also denied. |

:::caution
The [`requestPermission()` permission request algorithm](https://wicg.github.io/file-system-access/#api-filesystemhandle-requestpermission) (wicg.github.io) throws a `SecurityError` when it must prompt from a non-`Window` global, without transient activation, or from an origin different from the top-level origin. Keep the call inside the click handler that offers to restore access. Moving it into startup code or a worker removes the conditions the algorithm requires.
:::

## Examples

Core members work with origin-private file-system handles. The Chromium permission extension needs its own feature detection and an `<input type="file">` plus download route when a picker or permission is unavailable.

### Comparing handles without relying on their names

Paste this snippet into a secure-context page. Press **Compare handles** to obtain handles for `draft.txt` and `archive.txt`, then compare them. If `navigator.storage.getDirectory()` is unavailable, the file input still lets the user select a file and displays the metadata available from `File`.

```html
<button id="compare">Compare handles</button>
<input id="file-fallback" type="file" hidden>
<pre id="result"></pre>
<script type="module">
  const result = document.querySelector("#result");
  const fallback = document.querySelector("#file-fallback");

  document.querySelector("#compare").addEventListener("click", async () => {
    if (!("storage" in navigator) || !("getDirectory" in navigator.storage)) {
      fallback.hidden = false;
      fallback.click();
      return;
    }
    const root = await navigator.storage.getDirectory();
    const first = await root.getFileHandle("draft.txt", { create: true });
    const second = await root.getFileHandle("draft.txt");
    const other = await root.getFileHandle("archive.txt", { create: true });
    result.textContent = JSON.stringify({
      first: { name: first.name, kind: first.kind },
      sameDraft: await first.isSameEntry(second),
      sameAsArchive: await first.isSameEntry(other),
    }, null, 2);
  });

  fallback.addEventListener("change", () => {
    const file = fallback.files[0];
    result.textContent = file ? `${file.name} (${file.type || "unknown type"})` : "No file selected";
  });
</script>
```

The expected booleans are `true` for `sameDraft` and `false` for `sameAsArchive`, following the standard's locator comparison. To clean up the created OPFS entries, call `root.removeEntry("draft.txt")` and `root.removeEntry("archive.txt")`.

### Recovering when write permission is denied

This complete example asks for a local file only after a button click. The **Request write access** button checks write permission and calls `requestPermission()` from its own click handler when the state is `"prompt"`. Unsupported browsers and a denied request reveal a file input; selecting a file there makes the fallback produce a downloadable copy.

```html
<button id="choose">Choose local file</button>
<button id="write" disabled>Request write access</button>
<input id="copy-source" type="file" hidden>
<output id="status"></output>
<script type="module">
  let handle;
  const write = document.querySelector("#write");
  const source = document.querySelector("#copy-source");
  const status = document.querySelector("#status");

  function useDownloadFallback() {
    source.hidden = false;
    source.focus();
    status.value = "Choose a file below to download a copy";
  }

  document.querySelector("#choose").addEventListener("click", async () => {
    if (!("showOpenFilePicker" in window)) return useDownloadFallback();
    try {
      [handle] = await window.showOpenFilePicker();
      if (!("queryPermission" in handle) || !("requestPermission" in handle)) {
        return useDownloadFallback();
      }
      write.disabled = false;
      status.value = `Selected ${handle.name}`;
    } catch (error) {
      if (error.name !== "AbortError") throw error;
      status.value = "No file selected";
    }
  });

  write.addEventListener("click", async () => {
    try {
      let state = await handle.queryPermission({ mode: "readwrite" });
      if (state === "prompt") {
        state = await handle.requestPermission({ mode: "readwrite" });
      }
      status.value = `Write permission: ${state}`;
      if (state !== "granted") useDownloadFallback();
    } catch (error) {
      status.value = `${error.name}: choose a file for a downloadable copy`;
      useDownloadFallback();
    }
  });

  source.addEventListener("change", () => {
    const file = source.files[0];
    if (!file) return;
    const link = document.createElement("a");
    link.href = URL.createObjectURL(file);
    link.download = `copy-${file.name}`;
    link.click();
    URL.revokeObjectURL(link.href);
    status.value = `Downloaded copy-${file.name}`;
  });
</script>
```

Chrome's file-access documentation recommends querying a stored handle before requesting permission and making a fresh request when needed ([Stored file or directory handles and permissions](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access#stored-file-or-directory-handles-and-permissions), Chrome for Developers). This example performs the request during a user action and keeps the fallback independent of the handle that lost access.

## See also

- [File System Access API](/reference/capabilities/file-system-access/), for opening and saving user-selected files
- [Origin Private File System (OPFS)](/reference/storage/opfs/), for handles rooted in an origin's private bucket
- [Handle files](/guides/file-handling/), for a complete file-editing flow
- [File System Access compatibility data](/compatibility/file-system-access/), for measured support data about local picker entry points
- [File System Standard: FileSystemHandle interface](https://fs.spec.whatwg.org/#api-filesystemhandle) (fs.spec.whatwg.org)
- [File System Access: FileSystemHandle permission extension](https://wicg.github.io/file-system-access/#api-filesystemhandle-querypermission) (wicg.github.io)
- [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access) (developer.chrome.com)