1

Is there a polyfill for window.showOpenFilePicker (MDN)?

Lenard
  • 138
  • 1
  • 9
  • Does this answer your question? [What is the meaning of polyfills in HTML5?](https://stackoverflow.com/questions/7087331/what-is-the-meaning-of-polyfills-in-html5) – Sapt-Programmer Sep 09 '21 at 12:48
  • @Sapt-Programmer The OP does not appear to be asking about what polyfills are, they are asking if a polyfill exists for a specific function. That question is off-topic (as asking for off-site resources). The fact that they've answered their own question with such a polyfill does not excuse the poor question, just as the poor question does not excuse the poor answer. – Heretic Monkey Sep 09 '21 at 13:24
  • 1
    Did you search check the docs? What did you search for? – dagelf Sep 15 '21 at 08:34
  • Please share some code, that you have tried so far – Rajeev Singh Sep 15 '21 at 10:58

1 Answers1

4
function showOpenFilePickerPolyfill(options) {
    return new Promise((resolve) => {
        const input = document.createElement("input");
        input.type = "file";
        input.multiple = options.multiple;
        input.accept = options.types
            .map((type) => type.accept)
            .flatMap((inst) => Object.keys(inst).flatMap((key) => inst[key]))
            .join(",");

        input.addEventListener("change", () => {
            resolve(
                [...input.files].map((file) => {
                    return {
                        getFile: async () =>
                            new Promise((resolve) => {
                                resolve(file);
                            }),
                    };
                })
            );
        });

        input.click();
    });
}

if (typeof window.showOpenFilePicker !== 'function') {
    window.showOpenFilePicker = showOpenFilePickerPolyfill
}

Lenard
  • 138
  • 1
  • 9