1

I'm trying to do something weird with the web browser for a valid reason. The things I am trying to do and how I am doing it as follows.

  1. Create a new blank window upon clicking some button.

    var newWindow = window.open('', 'new window', spec, true);

  2. Add a input element of type file in the new window.

    newWindow.document.write('< input type="file" id="select-file" >');

  3. Dispatch a click event to the input element above immediately.

    newWindow.document.getElementById('select-file').dispatchEvent(new Event('click'));

All three steps are done in a function which is fired by clicking on the button mentioned in step 1. When the button is clicked, step 1 will surely create a new window and step 2 will insert the input element. However, step 3 would just pass by without any error. When I press the button again while the window is remained open, only then step 3 would work as I expect it to.

The only difference between the two cases is that step 1, 2 is gone through only when the window has to be created. Step 1, 2 will be ignored when the window is already opened and reused.

Therefore, I am assuming that there has to be something wrong with dispatching the mouse event. But I have no clue. Can someone elaborate on this?

The code I am trying to work on is similar to this example I made.

`http://jsfiddle.net/dansoonie/q8tzyx6z/`

I think it's not working because of some other JSfiddle issue, but take a look if my explanation is not understandable. Thanks in advance.

YoonSoo Lee
  • 167
  • 1
  • 2
  • 6

2 Answers2

1

For security purposes, triggering a click event from JS on an input element is disabled in most browsers

Check this question In JavaScript can I make a "click" event fire programmatically for a file input element?

Community
  • 1
  • 1
gafi
  • 12,113
  • 2
  • 30
  • 32
  • So, it's simply a security issue? I've suspected this but maybe I wanted to believe somehow it would work. My guess is that if you want to trigger the input with the created click event, it must be resulting from an actual click event fired by a user's action. Anyway, I wish at least the developer tools would let us know that the click event has been ignored for security issues. Thanks for the help – YoonSoo Lee Aug 20 '15 at 03:00
  • Yeah it'd be much better if the browsers could throw an error for such behavior – gafi Aug 20 '15 at 03:25
0

In the given fiddle change below line

$(newWindow.document.body).find('input-file').click();

to

$(newWindow.document.body).find('#input-file').click();

in jQuery to access an element using ID you must prepend with #

http://jsfiddle.net/santoshj/q8tzyx6z/1/

J Santosh
  • 3,808
  • 2
  • 22
  • 43