javascripttypescriptfile-system-access-api

File System Access API - Failed to execute 'requestPermission' on 'FileSystemHandle': User activation is required to request permissions


in my project im trying to change multiple files at once. A folder is opened and all files are listed, then changed and saved again. On saving im getting the following error

Failed to execute 'requestPermission' on 'FileSystemHandle': User activation is required to request permissions

Im basicly looping through an array of objects. Each holding the FileSystemFileHandler instance. Before saving the file, im querying or requesting for permission, but it doesnt work?

for await (let res of promises) {

    let { fileObject, arrayBuffer } = res

    const r = await this.verifyPermission(fileObject.handler, true)

    const stream = await fileObject.handler.createWritable()
    await stream.write(contents)
    await stream.close()
}



async 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
  }

Also should I ask for permission for each file im saving or once before I start looping?

Thanks in advance


Solution

  • It is not be required to ask for this permission several times. As soon as you have a FileSystemDirectoryHandle with read/write access, you are free to read and write multiple files.

    const dirPickOpts = {
      mode: 'readwrite',
      //startIn: 'pictures'
    };
    // window.showDirectoryPicker is not available in firefox
    const dirHandle = await window.showDirectoryPicker(dirPickOpts);
    // Use dirHandle to read and write files
    

    The error just complains that you trigger your fileHandle.requestPermission(opts) call not from a user even (e.g. a click on a button). Check the call stack, if you think it should have be triggered by a a user activation.