1
\$\begingroup\$

How to open an input file programmatically (javascript) in a reliably way?

The most modern versions of internet browsers prevent the opening of input files programmatically (javascript) under certain circumstances. For this reason I opened this thread to define a way to open input files so that we have no problems - or at least mitigate that risk - in future versions of internet browsers.


PLUS:

Some statements made in foruns (see references):

1

Yes, you can programmatically click the input element using jQuery (JavaScript), but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER.

2

The function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.

A little example (for illustration only):

Notice the comments in the code.

Apparently the safest way to open an input file is create this element dynamically.

We also have the approach using .trigger("click") (worked) and .click() (did not work). I couldn't understand why trigger worked and click didn't, because apparently they do the same thing.

IMPORTANT: For me there is no guarantee that the "trigger" solution will continue to work in future versions of "Chrome" or even other "browsers" like "Firefox". That is why I think it is important to find a safe way to resolve this issue.

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    function openInputFile() {

        // APPROACH 1 - Didn't work for me ("Chrome").
        $(JQ_TO_FIND_INPUT_FILE).click();

        // APPROACH 2 - Worked for me ("Chrome").
        $(JQ_TO_FIND_INPUT_FILE).trigger("click");

        // APPROACH 3 - Worked for me ("Chrome").
        var inputFile = $('<input type="file"/>');
        $(JQ_TO_FIND_A).after(inputFile);
        inputFile.click();

    }
    </script>
    <a href="#" onclick="openInputFile('theFile');">OPEN FILE DIALOG</a>
    <input type="file"/>

[Refs.: https://stackoverflow.com/a/43174934/3223785 , https://stackoverflow.com/a/21583865/3223785 , https://mariusschulz.com/blog/programmatically-opening-a-file-dialog-with-javascript , https://www.freecodecamp.org/forum/t/jquery-trigger-click-event-not-the-same-as-a-real-click/170745/3 ]

\$\endgroup\$
  • 4
    \$\begingroup\$ Greetings, this question is not a good fit for CodeReview as you are not asking for a code review. I am pretty sure this will get closed as off topic. \$\endgroup\$ – konijn Nov 4 '19 at 14:39
  • 1
    \$\begingroup\$ Why use jQuery and all its excessive overheads when input elements have native click method document.querySelector("input").click(); \$\endgroup\$ – Blindman67 Nov 4 '19 at 17:02