-3

I have a simple HTML file input that I can open with Javascript in Chrome but not in Firefox.

<input type="file" id="fileImportInput" style="display:none">

document.getElementById('fileImportInput').click(); // this works in Chrome but not Firefox

I'm not sure why this won't work in Firefox. I get no console error, etc. In Chrome the file browser opens and I can select my file no problem. Any ideas?

Thanks.

Edit: just to note that if I remove the display:none style from the input it makes no difference.

Alan Smith
  • 1,069
  • 4
  • 19
  • 23
  • How are you running the code? Is it top-level code run when the page loads, or in response to an event, or...? When I call `click` within the response to an event handler, this works in Firefox. (And even if it's in a timer callback for a timer initiated by a user event.) – T.J. Crowder Feb 27 '20 at 07:55
  • Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button; [here's how to do one](https://meta.stackoverflow.com/questions/358992/)). – T.J. Crowder Feb 27 '20 at 07:55
  • As it appears in the example, it's a security feature, you can't call `click` on `file` input without user interaction. – Teemu Feb 27 '20 at 07:56
  • 1
    @Teemu - But that's true in Chrome as well (just double-checked). – T.J. Crowder Feb 27 '20 at 07:56
  • I was running the Javascript snippet above in the browser console. – Alan Smith Feb 27 '20 at 07:57
  • 1
    @AlanSmith - Ah, that's often a bit of a gotcha. If something doesn't quite run as you expect in the console, try it for real. It doesn't work there because Firefox doesn't consider it to be in response to a user event. (Apparently Chrome does, I just confirmed what you've described.) – T.J. Crowder Feb 27 '20 at 07:58
  • This is actually a duplicate https://stackoverflow.com/questions/1829774/jquery-simulating-a-click-on-a-input-type-file-doesnt-work-in-firefox – Alexandre Elshobokshy Feb 27 '20 at 08:27

1 Answers1

0

I actually got it working. Firefox has a default setting enabled to block pop ups. Just go to Options and check it off. Strange that it includes file dialogs in it's block list.

https://support.mozilla.org/en-US/kb/pop-blocker-settings-exceptions-troubleshooting#w_is-the-pop-up-blocker-on-and-enabled-for-this-sitehttps://support.mozilla.org/en-US/kb/pop-blocker-settings-exceptions-troubleshooting#w_is-the-pop-up-blocker-on-and-enabled-for-this-site

Alan Smith
  • 1,069
  • 4
  • 19
  • 23
  • 2
    **Don't do that** in the normal case, the setting is enabled for a reason. Obviously, a one-off situation is different, but don't browse the web with that disabled. :-) – T.J. Crowder Feb 27 '20 at 08:01
  • 2
    Also not an compatible way to maintain that for public use. You can't force people to have same browser settings. Recommend use different approach and let the browser stay in basic settings – Jayr Feb 27 '20 at 08:13