ファイルユーザージェスチャー必須判定中...
File System Access API
ローカルファイルをユーザーの許可のもとで開き、同じファイルへ直接上書き保存できるAPI。Webアプリでネイティブ級のファイル編集を実現する。
1対応判定
| ブラウザ | 対応バージョン |
|---|---|
| Chrome | 86+(Android 132+) |
| Firefox | 未対応 |
| Safari | 未対応 |
備考: Chromium限定。OPFS(オリジンプライベートファイルシステム)は別物
2権限フロー
権限不要
API呼び出しだけで動く。プロンプトも操作起点の縛りもない
ユーザージェスチャー必須このAPI
ボタンクリック等のユーザー操作の中でしか呼べない。プロンプトは出ない
権限プロンプトあり
呼び出すとブラウザが許可/ブロックのプロンプトを表示し、ユーザーが選ぶ
iOS独自requestPermission
iOSではrequestPermission()を操作起点で呼び、明示的に許可を得る
showOpenFilePicker() はユーザージェスチャー必須。書き込み時には「変更の保存を許可しますか」という権限プロンプトが別途表示される。
3ライブデモ: ローカルの.txt/.mdを開いて上書き保存するミニエディタ
4コードスニペット
TypeScript(要約版)
// ファイルを開く(ユーザージェスチャー必須)
const [handle] = await window.showOpenFilePicker!({
types: [
{
description: "テキスト",
accept: { "text/plain": [".txt", ".md"] },
},
],
});
// 読み込み
const file = await handle.getFile();
const text = await file.text();
editor.value = text;
// 同じファイルへ上書き保存
// (初回は「変更の保存を許可しますか」プロンプトが出る)
async function save(content: string) {
const writable = await handle.createWritable();
await writable.write(content);
await writable.close(); // closeで実際にディスクへ反映
}
// 権限状態の確認もできる
const perm = await handle.queryPermission({ mode: "readwrite" });
console.log(perm); // "granted" | "prompt" | "denied"