I've implemented a file download button through ajax using code similar to this answer. I have code that looks something like this:
$('#download-link').on('click', function (event) {
event.preventDefault();
var link = $('#download-link').attr('href');
$.ajax({
url: link,
success: function (result) {
var blob = getBlob(result);
var a = document.createElement('a');
var url = (window.URL ? URL : webkitURL).createObjectURL(blob);
a.href = url;
a.download = 'somefilename.txt';
a.style.display = 'none';
document.body.appendChild(a);
try {
a.click();
}
catch (err) {
//fallback. if .click() is unavailable display a new button for user to get file.
a.style.display = '';
a.innerText = 'Get File';
var downloadButton = document.getElementById('download-link');
downloadButton.style.display = 'none';
}
}
});
});
So essentially, we're creating an object URL, creating an <a>
element with Href of the object URL and calling Click()
on that element to download the file. Some browsers will throw an error at that point, so as a fallback we catch the error and display the created button, so that the user can press and get the file.
The problem is that some browsers (seems to be on iOS, and older versions of Android) will simply ignore the Click()
call. I know that I could use browser sniffing to deal with this, but I don't consider that a very good solution. Is there anything more elegant that I can do to detect this situation and use my fallback?