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

浏览器兼容性

另见