GoogleChromeLabs / browser-fs-access

File System Access API with legacy fallback in the browser
https://googlechromelabs.github.io/browser-fs-access/demo/
Apache License 2.0
1.38k stars 84 forks source link

Restoring a FileHandle #81

Closed steveruizok closed 2 years ago

steveruizok commented 2 years ago

Hi, I'm trying to restore a FileHandle after refreshing a page where a handle had been previously set. I am able to save and load the handle from indexdb as described in this StackOverflow question, however the fileSave method does not appear to accept it.

Here's the chain of events.

  1. Save file
  2. Choose name and destination via native window
  3. Confirm (and persist file handle in state and in idb)
  4. Make changes to file
  5. Save file again
  6. Changes save in background
  7. Reload window (and restore file handle to state)
  8. Save file
  9. Back to step number 2

I would expect number 8 to go to step number 5, rather than step number 2.

I've checked also on Excalidraw, the same behaviour appears to be happening there.

tomayac commented 2 years ago

You might be missing the permissions step. Here's a working code sample of one of my apps:

const checkPermissions = async (handle) => {
  const options = { mode: 'read' };
  if ((await handle.queryPermission(options)) === 'granted') {
    return true;
  }
  if ((await handle.requestPermission(options)) === 'granted') {
    return true;
  }
  return false;
};

// …snip…
  try {
    // Start where the user left off.
    // (This uses https://github.com/jakearchibald/idb-keyval 
    // for convenience.)
    const handle = await get(FILE_HANDLE);
    if (handle && (await checkPermissions(handle))) {
      const file = await handle.getFile();
      // …snip…
    }
  } catch (err) {
    console.error(err.name, err.message);
    await del(FILE_HANDLE);
  }
// …snip…

Does this work for you?

steveruizok commented 2 years ago

Works! Though strangely if I set the mode to readwrite the permissions pop-up comes up twice.

tomayac commented 2 years ago

Great to hear! This may be a temporary thing, the final permission flow may still change. Closing the Issue then.