Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate file selection with javascript?

Tags:

javascript

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 ?

like image 851
Alex Ng Avatar asked Sep 05 '25 03:09

Alex Ng


1 Answers

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.

like image 148
Pekka Avatar answered Sep 07 '25 21:09

Pekka