I've been looking for a good way to use javascript to initiate the download of a file, just as this question suggests. However these answers not been helpful. I then did some xbrowser testing and have found that an iframe works best on all modern browsers IE>8.
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 to style 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 .visuallyHidden in html5boilerplate
I prefer this to the javascript window.open method because if the link is broken the iframe method simply doesn't do anything as opposed to redirecting to a blank page saying the file could not 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();