最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How do I execute some javascript after a file is downloaded? - Stack Overflow

programmeradmin1浏览0评论

I have a page with a link to a file. When the link is clicked I use the code below to show a loading message:

$('#TerritoriesToExcelLink').click(function() {
    $('#TerritoriesToExcelLoading').show();
    window.location.href = $(this).attr('href');
});

I'd like to hide the message once the file is downloaded and the save dialog pops up in the browser.

I've tried adding some code that fires on ready() but that seems to just run straight away (presumably since the page is already loaded even if the file isn't) so the loading message never gets displayed.

How can I hide the loading message once the file has been pletely downloaded?

I have a page with a link to a file. When the link is clicked I use the code below to show a loading message:

$('#TerritoriesToExcelLink').click(function() {
    $('#TerritoriesToExcelLoading').show();
    window.location.href = $(this).attr('href');
});

I'd like to hide the message once the file is downloaded and the save dialog pops up in the browser.

I've tried adding some code that fires on ready() but that seems to just run straight away (presumably since the page is already loaded even if the file isn't) so the loading message never gets displayed.

How can I hide the loading message once the file has been pletely downloaded?

Share Improve this question asked Feb 19, 2013 at 9:33 George DuckettGeorge Duckett 32.5k11 gold badges101 silver badges166 bronze badges 4
  • Doesn't assigning to window.location.href just blow away away your whole loaded page? What else is going on here? – Plynx Commented Feb 19, 2013 at 9:36
  • 2 I'd say: you can't, because JS by its own is not able to know when a Download has been finished. – sascha Commented Feb 19, 2013 at 9:37
  • 1 @Plynx Not if the new URL is for a download. – Anthony Grist Commented Feb 19, 2013 at 9:39
  • Possible duplicate of Detect when browser receives file download – Sᴀᴍ Onᴇᴌᴀ Commented Jan 19, 2017 at 18:28
Add a ment  | 

3 Answers 3

Reset to default 3

Have your server send a random cookie that you specify from your client-side code with your download in the HTTP headers. Poll in your Javascript to check for the presence of the cookie. This should tell you when the browser has your file.

If you aren't opposed to using flash...

You could create an invisible flash object on the page, then when you click the download link, you could trigger flash to download the file, then handle the flash download plete event and use the ExternalInterface API to raise the event in javascript.

This is not possible to do with front end javascript, there is no way for it to retrieve the progress of a download and it doesn't have any events relating to downloads.

I don't think tracking the progress can be done with server side languages either.

发布评论

评论列表(0)

  1. 暂无评论