FileSystemHandle: queryPermission() 方法

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

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

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

FileSystemHandle 接口的 queryPermission() 方法用于查询当前句柄的当前权限状态。

语法

js
queryPermission(descriptor)

参数

descriptor 可选

一个指定要查询的权限模式的对象。选项如下:

'mode' 可选

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

返回值

一个 Promise,它会解析为 PermissionStatus.state,其值为 'granted''denied''prompt'。它也可能由于以下任一异常而拒绝。

如果解析为 "prompt",则在该句柄上执行任何操作之前,网站必须先调用 requestPermission()。如果解析为 "denied",则任何操作都会被拒绝。通常,从本地文件系统句柄工厂返回的句柄,其读取权限状态最初会解析为 "granted"。但是,除了用户撤销权限外,从 IndexedDB 检索到的句柄也可能解析为 "prompt"。

异常

TypeError

如果 mode 的值不是 'read''write''readwrite',则会抛出此异常。

示例

以下异步函数在用户已授予文件句柄读取或读写权限时返回 true。如果尚未授予权限,则会请求权限。

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-querypermission

浏览器兼容性

另见