DOMException:当前上下文中的用户代理或平台不允许该请求

Jam*_*tes 13 file-system-access-api

当尝试使用FileSystemFileHandlegetFile()的方法访问文件时,可能会发生此错误:DOMException: The request is not allowed by the user agent or the platform in the current context.

这段代码的工作原理:

async function getTheFile() {
  // open file picker
  [fileHandle] = await window.showOpenFilePicker(pickerOpts);

  // get file contents
  const fileData = await fileHandle.getFile();
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您存储fileHandle(例如使用 IndexedDB)的目的是即使在页面刷新后仍保留对文件的访问,则它将不起作用。刷新页面后,该getFile()方法将抛出 DOMException 错误。

这是怎么回事?

Jam*_*tes 18

刷新页面(或关闭应用程序的所有选项卡)后,浏览器不再有权访问该文件。

有一个可用于在尝试读取文件之前确定是否可以访问该文件的queryPermission()方法。FileSystemHandle

来自有用的 web.dev 文章的示例:

async function verifyPermission(fileHandle, readWrite) {
  const options = {};
  if (readWrite) {
    options.mode = 'readwrite';
  }
  // Check if permission was already granted. If so, return true.
  if ((await fileHandle.queryPermission(options)) === 'granted') {
    return true;
  }
  // Request permission. If the user grants permission, return true.
  if ((await fileHandle.requestPermission(options)) === 'granted') {
    return true;
  }
  // The user didn't grant permission, so return false.
  return false;
}
Run Code Online (Sandbox Code Playgroud)

一旦权限 ===,此函数将返回 true ;如果权限为或 ,granted则重新提示用户访问。deniedprompt