FileSystemHandle:requestPermission() 方法

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

备注: 此特性在 Web Worker 中可用。

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

FileSystemHandle 接口的 queryPermission() 方法用于为文件句柄请求读取或读写权限。

语法

js
requestPermission(descriptor)

参数

descriptor 可选

一个对象,指定需要查询的权限模式,包含以下选项:

'mode' 可选

可以是 'read''readwrite'

返回值

一个兑现为 PermissionStatus.statePromise,其值为 'granted''denied''prompt'。它也可能因出现以下异常而被拒绝。

异常

TypeError

如果没有指定参数或者 mode 的值不是 'read''readwrite',则抛出此异常。

SecurityError DOMException

在下列情况之一发生时抛出:

  • 该方法是在与顶级上下文不同源的上下文(例如跨源 iframe)中调用的。
  • 没有瞬态用户激活,例如按下按钮。这包括当句柄处于无法使用用户激活的非 Window 上下文(例如 Worker)中时。

安全

瞬态用户激活是必需的。用户必须与页面或 UI 元素进行交互才能使该特性正常运行。

示例

以下异步函数会在句柄没有获得授权时请求权限。

js
// fileHandle 是一个 FileSystemFileHandle
// withWrite 是一个布尔值,如果要求写入则需传入 true

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

  // 检查是否已经拥有相应权限,如果是,返回 true。
  if ((await fileHandle.queryPermission(opts)) === "granted") {
    return true;
  }

  // 为文件请求权限,如果用户授予了权限,返回 true。
  if ((await fileHandle.requestPermission(opts)) === "granted") {
    return true;
  }

  // 用户没有授权,返回 false。
  return false;
}

规范

Specification
File System Access
# api-filesystemhandle-requestpermission

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
requestPermission
Experimental

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Experimental. Expect behavior to change in the future.

参见