Reputation: 41
I try to simulate programmatically the user clicking on an html element type input:file to upload a file to a website with javascript on firefox browser. The following javascript codes in my javascript file simulates and opens the file dialog:
var target_element;
var dispatchMouseEvent = function(target, var_args) {
var e = document.createEvent("MouseEvents");
e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
target_element = window.content.document.getElementById("DivElement");
dispatchMouseEvent(target_element, 'mouseover', true, true);
dispatchMouseEvent(target_element, 'mousedown', true, true);
dispatchMouseEvent(target_element, 'mouseup', true, true);
dispatchMouseEvent(target_element, 'click', true, true);
but I can't find a way to simulate programmatically the selection of a file on the file dialog like a user selecting a file and click on the button Open of the file dialog. Is that possible to do it with javascript ?
Upvotes: 4
Views: 2626
Reputation: 4072
Create a input file and fire the click
event.
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.addEventListener('change', event => { console.log('Attached!') });
input.click();
Upvotes: 0
Reputation: 449495
This is going to be impossible, and for good reason. If you could automate the selection of a file on client side, you would open the door to massive breaches of security and privacy.
Upvotes: 6