Trigger click on input=file on asynchronous ajax done()
Solution 1:
Its not possible right now to open a file popup window from an async ajax callback due to w3c recommended security features in the browsers.
In the file input element's activation behavior it first checks if the algorithm is allowed to show a popup, if not then abort the next steps without doing anything else. from w3c.org
An algorithm is allowed to show a popup if any of the following conditions is true:
- The task in which the algorithm is running is currently processing
an activation behavior whose click event was trusted.(trusted events : Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the
DocumentEvent.createEvent("Event")
method, modified using theEvent.initEvent()
method, or dispatched via theEventTarget.dispatchEvent()
method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false. otherwise. http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#trusted-events.) -
The task in which the algorithm is running is currently running the event listener for a trusted event whose type is in the following list:
- change
- click
- dblclick
- mouseup
- reset
- submit
- The task in which the algorithm is running was queued by an algorithm that was allowed to show a popup, and the chain of such algorithms started within a user-agent defined timeframe.
w3c.org
In your code the click event is not triggered by the user but its triggered by the ajax complete callback. Here the browser declares that the event cannot be trusted to open a popup. In some browsers you can see an isTrusted
attribute set to true if the event is declared as trusted.https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
Note
Different browsers trap the difference between a script activated cick and a real user using different methods.
What you can do in this scenario is to disable the file input button(or the entire form) and enable after ajax is done. That way the user wont click on the upload button until the ajax request gets completed. As of now there is no other way to do both in one click since there is a timeframe limit also for opening popup. When I checked in chrome the timeframe is 1000ms. 1000ms after the user action, window will not get opened.