calling window.showSaveFilePicker() outside a safe context in javascript

Viewed 41

I'm using the javascript file API in the browser, to force the opening of the dialog window for downloading files, my goal is to make this window always open when there is a download, even if the user has defined the download in their browser if automatic.

So for that I'm using the window.showSaveFilePicker() function to open the window, and then add a file (Blob) coming from a download. The problem is that the call to window.showSaveFilePicker() can only be performed in a safe context according to the documentation at: https://web.dev/file-system-access/

That is, if I call this function like this:

    async function DownloadFile(){
      async function startDialogWindow() {
    
        const options = {
           types: [
             {
               description: 'Text Files',
               accept: {
                 'text/plain': ['.txt'],
               },
             },
           ],
         };
        // an exception will be thrown here
        const handle = await window.showSaveFilePicker(options);
      }
    
      await startDialogWindow()
    }

an exception "DOMException: Failed to execute 'showSaveFilePicker' on 'Window': Must be handling a user gesture to show a file picker." will be released.

but if the same call is made like this:

buttonTest.addEventListener('click', async() => {
  const handle = await window.showSaveFilePicker(options);
} )

no exception occurs.

Given this, is there any way to run window.showSaveFilePicker within an unsafe context?

I also tried:

let handle = null;
let buttonTest = document.createElement('button');
buttonTest.addEventListener('click', async() => {
      handle = await window.showSaveFilePicker(options);
} );
buttonTest.click()

but I was not successful.

1 Answers

I found the answer to the problem. I can't explain why the solution worked, but the exception stopped being thrown when I removed all the "debugger" keywords from my code, i.e. letting the process flow normally without stopping for debugging solved the problem. this is very strange, but that's what was happening.

Related