File open dialogue opens twice

Not sure if anyone else is getting the same issue, but when I run this basic function, the File picker opens the selected file, then opens the file picker again.

If I close the second instance, then run the function again, it runs as expected and opens a selected file.

const fs = require("uxp").storage.localFileSystem

async function openFile() {
   const file = await fs.getFileForOpening();
      await app.open(file);
      return
}

Is this code the correct way to open a file with the picker?

Try it this way:

async function openFile() {
   const file = await fs.getFileForOpening();
   if (file) {
      await app.open(file);
   } else {
      return;
   }
}

The else block is for catching the case if the user clicks on ‘Cancel’ in the file dialog.

Hmm it’s interesting as i’m getting the same behaviour with your code

I have no idea what’s causing the picker to open twice.

Are you running that from an sp-button? I had the same issue with the folder picker running from sp-buttons. The event listener semmed to run in an infinite loop. Switching to a native HTML button fixed it. I posted about this a few months ago and other had the same problem too.

Since that time, I implemented a fix for the space and enter key focus issue. I then tried this with sp-buttons again for the folder picker and it also solved the folder picker issue too. I think the button was triggering again when the user clicked to select a folder which is why the folder picker kept opening again. The “nofocus” fixed Kerri Shots gave me in this post fixed the issue.

That’s it - good find. Adding that code fixes it.

HTML
<sp-button nofocus>Hi</sp-button>

JS

Array.from(document.querySelectorAll("[nofocus]:not([data-handler-added])"), el => {
    el.addEventListener("focus", evt => evt.target.blur());
    el.setAttribute("data-handler-added");
});

Where would be a proper place to place that JS snippet in my JS file? Or is there a fix from Adobe in the meantime?

It really shouldn’t matter. I just put it at the bottom.

1 Like