Programmatically Opening a File Dialog with JavaScript
I want to take a quick look at file uploads using HTML and JavaScript. Nowadays, many websites don't show the raw <input type="file">
element anymore. Take Facebook, for example:
When you click on the photo button highlighted above, the native file dialog will open:
It's not hard to make that functionality work in modern browsers. In essence, it boils down to triggering a click event on a hidden <input type="file">
whenever the photo button is clicked. Here's a tiny, but working HTML example that reproduces that functionality:
<html>
<body>
<input type="file" style="display: none" />
<button>Open File Dialog</button>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script>
$("button").on("click", function () {
$("input").trigger("click");
});
</script>
</body>
</html>
And indeed, if we try it out, clicking the "Open File Dialog" button opens the file dialog, as we would expect. Let's now try to automatically open the file dialog immediately after the page has loaded:
<script>
$("input").trigger("click");
</script>
That doesn't seem to work. How about delaying the call to the trigger
method?
<script>
setTimeout(function () {
$("input").trigger("click");
}, 1000);
</script>
That doesn't seem to work, either. How come that in the first example, the file dialog was opened successfully? The reason that the first example worked is that the click event was triggered within a code block that was the handler of a user-initiated event.
When we clicked the button, the registered handler function was executed, and the browser kept track of the fact that it was the user who initiated that button click event, not some piece of code. Outside of such user-initiated events, file dialogs cannot be opened programmatically.
Similarly, modern browsers generally don't open a new window when the window.open()
is not called from within the handler of a user-initiated event. Instead, they'll display a warning like this one: