I was looking for a good way to use javascript to start a file download, like this question. However, these answers did not help. Then I did some xbrowser testing and found that iframe works best in all modern IE> 8 browsers.
downloadUrl = "http://example.com/download/file.zip"; var downloadFrame = document.createElement("iframe"); downloadFrame.setAttribute('src',downloadUrl); downloadFrame.setAttribute('class',"screenReaderText"); document.body.appendChild(downloadFrame);
class="screenReaderText"
is my class for stylish content that is present but not viewable.
CSS
.screenReaderText { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; }
same as .visiddenHidden in html5boilerplate
I prefer this for the javascript window.open method, because if the link is broken, the iframe method just does nothing and does not redirect to a blank page, saying that the file cannot be opened.
window.open(downloadUrl, 'download_window', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0'); window.focus();
alockwood05 Aug 01 '12 at 21:05 2012-08-01 21:05
source share