I have an file-browser input in my HTML.
I have another button with ID choose-file-button
There's some browser security magic going on here. When using timeouts or intervals or any other methods I try, the code carries on as normal but the browser simply refuses to open a file upload dialog. This is probably deliberate, to stop malicious JS from trying to grab users' files without consent. However, if you bind to a click event on a link, it works perfectly using jQuery or regular JS.
Edit: As suspected, most browsers keep track of whether an event is trusted or not based on the type of event and whether it was created by the user or generated programmatically. Se this answer for the full details. As you can see, since keyboard events aren't in the list, they can never be trusted.
Test JSFiddle
$("#mylink").click(function () {
$("#myfile").click();
});
$(window).bind('keydown', function (e) {
if (e.ctrlKey || e.metaKey) {
switch (String.fromCharCode(e.which).toLowerCase()) {
case 'o':
e.preventDefault();
console.log("1a");
$("#myfile").click();
//alert("hello");
console.log("1b");
return false;
}
}
return true;
});
I think there are only two options here, and they're both workarounds, not solutions.
Addendum: I also tried using pure JavaScript in Firefox to grab a click event and check to see if it's trusted using the isTrusted
property. For the clicks on the link, it returned true
. However, attempting to store and re-use the event elsewhere doesn't work, because it's already been dispatched by the time you get a reference to it. Also, unsurprisingly, creating a new event and attempting to set isTrusted = true
doesn't work either since it's read-only.