FileSystemHandle: requestPermission() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

注意:此功能在 Web Workers 中可用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

FileSystemHandle 介面的 requestPermission() 方法用於請求檔案控制代碼的讀取或讀寫許可權。

語法

js
requestPermission(descriptor)

引數

descriptor 可選

一個物件,指定要查詢的許可權模式。選項如下:

'mode' 可選

可以是 'read''write''readwrite'

返回值

一個 Promise,它會解析為 PermissionStatus.state,該狀態為 'granted''denied''prompt' 之一。它也可能因以下異常之一而拒絕。

異常

TypeError

如果在未指定引數或 mode 不是 'read''write''readwrite' 時呼叫此方法,則會丟擲此異常。

SecurityError DOMException

在以下情況之一中丟擲

  • 該方法是在與頂層上下文(即跨域 iframe)非 同源 的上下文中呼叫的。
  • 沒有瞬時使用者啟用(例如按鈕點選)。這包括在無法消耗使用者啟用的非視窗上下文(例如 worker)中呼叫該控制代碼時。

安全

需要瞬時使用者啟用。使用者必須與頁面或 UI 元素進行互動才能使此功能正常工作。

示例

以下非同步函式在尚未授予許可權時請求許可權。

js
// fileHandle is a FileSystemFileHandle
// withWrite is a boolean set to true if write

async function verifyPermission(fileHandle, withWrite) {
  const opts = {};
  if (withWrite) {
    opts.mode = "readwrite";
  }

  // Check if we already have permission, if so, return true.
  if ((await fileHandle.queryPermission(opts)) === "granted") {
    return true;
  }

  // Request permission to the file, if the user grants permission, return true.
  if ((await fileHandle.requestPermission(opts)) === "granted") {
    return true;
  }

  // The user did not grant permission, return false.
  return false;
}

規範

規範
檔案系統訪問
# api-filesystemhandle-requestpermission

瀏覽器相容性

另見