Download binary without triggering onbeforeunload Download binary without triggering onbeforeunload ajax ajax

Download binary without triggering onbeforeunload


The best way to do this is indeed by constructing an iframe and triggering the download from there.

I have tested this in Chrome, IE6+ and Firefox and this approach seems to work in all of them.

Example code:

function DownloadFile(filePath) {    var downloadIframe = $('<iframe />',         {            id    :    'downloadIframe'                }).appendTo('body');    downloadIframe.attr('src', filePath);}

This will only work properly for a one off download (as we've hard coded an id), if you are triggering multiple downloads, then I suggest you reuse the iframe by storing it in a more widely accessible variable.


Add the download attribute to the a tag, which seems to prevent onbeforeunload from firing:

<a download href="mysite.com"></a>

From this answer.


I would guess using the target attribute on the link could do the trick.

<a href="http://www.example.com/somefile.zip" target="_blank">download</a>

Will not validate (unless using frameset doctype) but it might work.. It will create a new tab or window and then pop a file download (if the http header says it should), but it might leave the new tabs/windows open, or it might close them after saving...

On the other hand I think having a onbeforeunload handler that you sometimes do not want to trigger sounds suspicious, why do you need that anyway?