-4

I am trying to write a webpage that will download "myfile.docx" and then close itself on download complete. Here's what I got

   <html>
    <body>
        <form method='get' action='myfile.docx' name='startDownload'>
        </form>
        <script>
        document.startDownload.submit();
        window.close();
        </script>
    </body>
    </html>

the problem is the page doesn't close. Please make it short

prasanth
  • 22,145
  • 4
  • 29
  • 53
  • use this for Edge and Chrome `window.top.close();` , but you're implementing it simpler than you should – Motassem Kassab Oct 22 '16 at 10:16
  • also I guess it's not possible to close the window when the download finishes, rather you can close it when the download starts, but this a very bad practice unless your window is a pop up – Motassem Kassab Oct 22 '16 at 10:17

2 Answers2

1

First of all, the submit method does not block, so the window.close method will be invoked immediately. I am not aware of any method to receive a notification, when the file download has finished. Second of all, you may only invoke window.close on a window that was opened via a script, not by user intervention (see https://stackoverflow.com/a/19768082/657401).

Community
  • 1
  • 1
Witiko
  • 3,167
  • 3
  • 25
  • 43
0

This works:

<html>
<body>
<a href='myfile.docx' id='myfile' name='fileToDownload'>Download</a>
<script>

document.getElementById('myfile').click();
console.log(new Date());
console.log('Dude!');
sleep(4000);//wait for the file to finish downloading
console.log(new Date());

window.close()
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
</script>
</body>
</html>
  • By calling your `sleep` function, you will freeze the user's browser for 4 seconds (in threaded browsers, you may freeze just the current window). How about `setTimeout(function() { window.close() }, 4000);`? Also, the file may not finish downloading in 4 seconds, although that does not really matter, because the browser will keep on downloading the file if you have other windows open. If this is the only open window, then it is unlikely that it was opened using a script, so `window.close` will not do its thing. Overall, I don't think you understand what you are doing. – Witiko Oct 22 '16 at 14:09