2

This question is not about the jQuery.fn.ready().

I open a new window with window.open() for file download, and wants to close the window after the download is started. Most browsers will continue the file download so I don't need to wait until the download is finished.

The problem is when I close the window with jQuery.fn.ready(), the file download is skipped straight away.

Here is what I tried and failed:

var w = window.open(...);

$(w).load(); // failed
$(w.document).load(); // failed
$(w.document).contents().load(); // failed
$(w.document).contents().find('body').load(); // failed

EDIT:

Adding jsFiddle for easy demo: http://jsfiddle.net/vicary/Yjkt8/1

EDIT 2:

By Jonny Sooter's answer, updated jsFiddle with a working version http://jsfiddle.net/vicary/Yjkt8/4.

Vicary
  • 1,026
  • 1
  • 15
  • 35

2 Answers2

1

You can try this if you know the downloading time.

jQuery(window).load(function () {
    alert('page is loaded');

    setTimeout(function () {
        alert('page is loaded and 1 minute has passed');   
    }, 60000);

});
Aleksander Blomskøld
  • 18,374
  • 9
  • 76
  • 82
Amrendra
  • 2,019
  • 2
  • 18
  • 36
1
$(function() {
    $('button').click(function() {
        var w = window.open(),
            d = w.document,
            s = d.createElement("script");

        s.type = "text/javascript";
        s.innerHTML = ";(function(){window.close();})();";

        d.getElementsByTagName("head")[0].appendChild(s);
    });
});

Update:

For chrome you can try:

window.open('', '_self', ''); //bug fix
window.close();

Or try:

window.self.close();
Jonny Sooter
  • 2,417
  • 1
  • 24
  • 40
  • Seems, legit. Corrected your script to make it work properly. – Vicary Feb 26 '13 at 18:26
  • Still not working, Chrome seems preventing code injection to `window.close()` alone. Loading a page that calls this function works. – Vicary Feb 26 '13 at 18:53