Simulate the onchange event when clicking type is file

I want to implement a click event with type as file as soon as I enter the page, and then get the selected image information. My code is

var _file = document.createElement("input");
_file.setAttribute("type", "file");
_file.setAttribute("style", "display:none;");
_file.setAttribute("height", "0px");
_file.setAttribute("width", "0px");
_file.setAttribute("id", "_file-id");
document.body.appendChild(_file);
document.getElementById("_file-id").click();
document.getElementById("_file-id").onchange = function(e) {
    alert(1)
}

write this, no matter how you look at it, but it does not trigger the click event of file directly on Google browser, but it triggers the click event on ie browser, but when I select the picture, I do not execute the onchange event. I ask God to tell me that it is written correctly and is compatible with these two browsers.

Thank you very much!

Test results:

  1. Google Chrome version 71.0.3578.98 (official version) (64-bit)
  2. Firefox Quantum 64.0 (64 bit)
  3. IE 11.194.17763.0 failed the test

personal opinion:
about compatibility, it is recommended to find an open source framework to do it, personal implementation will always have a lot of unexpected problems.


for security reasons, this function is generally not allowed, and only after the user has an interaction. Here, the interaction usually refers to clicking or touching the screen.
A replacement scheme is recommended. For example, create a new file box setting to deviate from the canvas or set opacity to transparent to trigger the click event of the file box when the page uses an overlay to cover the page user's clicks or other events.

  

try trigger

Menu