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.


Some statements made in foruns (see references):


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.


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").

        // APPROACH 2 - Worked for me ("Chrome").

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

    <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 ]

  • 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