Why does ShowDirectoryPicker hang?

324 Views Asked by At

I try to add folder scanning into my web page. Folder selection works fine and I get prompted if I want to allow the access to selected folder. But then nothing happens. In console I see "1" as the last log entry, so await never returns.

Any ideas what I should do?

jQuery(document).ready(function ($) {
  const butDir = document.getElementById('butDirectory');
  butDir.addEventListener('click', async() => {
    console.log("1");
    const dirHandle = await window.showDirectoryPicker();
    console.log("2");
    const promises = [];
    for await (const entry of dirHandle.values()) {
      if (entry.kind !== 'file') {
        continue;
      }
      promises.push(entry.getFile().then((file) => `${file.name} (${file.size})`));
    }
    console.log(await Promise.all(promises));
  });
});
2

There are 2 best solutions below

0
Riho On BEST ANSWER

OK, got it working. Instead of having the code inside jquery.ready() I had to move it outside:

async function getDir() {
  const dirHandle = await window.showDirectoryPicker();
}

and call it directly from HTML

<input type="button" ... onclick="javascript:getDir();"/>
2
Lajos Arpad On

The documentation tells us that transient user activation is needed.

enter image description here. It also needs to be opened in its own tab, see Window.showDirectoryPicker() not working in Google Chrome 107

So, you will need to comply to the terms the documentation asks you to comply to and if the problem is still unresolved, then you will need to edit your question, provide more information and ping me here in the comment section.