0

I am running into a weird problem. Not sure if it is due to the security concern of any other reason. I have following piece of code:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<button onclick='someThgTemp()'>TRY</button><br /><br /><br /><br />
<label id='labelId' for='some'>sdfasdf</label>
<input id='some' type='file'/>
</body>
<script>
var someThg = function someThg(){
alert(2);
console.log(document.getElementById('labelId'));
  document.getElementById('labelId').click();
}

function someThgTemp(someThg){
alert('1');
var that = this;
  window.setTimeout(function(){

  that.someThg();
 }, 3000)

alert(3)

}
</script>
</html>

So on this line:

<button onclick='someThgTemp()'>TRY</button>

the file chooser dialog is not shown

Where as if I change the above line to following

<button onclick='someThg()'>TRY</button>

The file chooser is called.Please let me know what I am doing wrong and what is the alternative for it.

The reason to do this being, before showing the file browser I need to validate something. If validated then only I want to show the user file browser.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Nitin Mesta
  • 1,504
  • 19
  • 32

2 Answers2

1

For security reasons you can not trigger manually a click event that open popup or open a dialog file in asynchronous call with too much delay (setTimeout use after 3 seconds). The user must associate directly the click to the event that you want that happens.

Try to set 1000 milliseconds instead of 3000. (and delete all alerts)

Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
0

I guess you are messing up with this and that. I would go ahead in this way:

window.onload = function () {
  theBtn = document.getElementById("myBtn");
  theBtn.onclick = function () {
    theFile = document.getElementById("some");
    theFile.click();
  };
};
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<button id="myBtn">TRY</button>
<br />
<br />
<br />
<br />
<label id='labelId' for='some'>sdfasdf</label>
<input id='some' type='file' />

Using a Timer - Browse window comes after a second.

window.onload = function () {
  theBtn = document.getElementById("myBtn");
  theTimeFunc = function () {
    theFile = document.getElementById("some");
    theFile.click();
  };
  theBtn.onclick = function () {
    setTimeout(theTimeFunc, 1000);
  };
};
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<button id="myBtn">TRY</button>
<br />
<br />
<br />
<br />
<label id='labelId' for='some'>sdfasdf</label>
<input id='some' type='file' />
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252