I have a very similar requirement specified here.
I need to have the user\'s browser start a download manually when $(\'a#someID\').click();
But
To improve Imagine Breaker 's answer, this is supported on FF & IE :
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.dispatchEvent(evt);
}
In other words, just use a dispatchEvent
function instead of click()
;
I ended up using the below snippet and it works in most browsers, not tested in IE though.
let data = JSON.stringify([{email: "test@domain.com", name: "test"}, {email: "anothertest@example.com", name: "anothertest"}]);
let type = "application/json", name = "testfile.json";
downloader(data, type, name)
function downloader(data, type, name) {
let blob = new Blob([data], {type});
let url = window.URL.createObjectURL(blob);
downloadURI(url, name);
window.URL.revokeObjectURL(url);
}
function downloadURI(uri, name) {
let link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
function downloadURI(uri, name) {
let link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
function downloader(data, type, name) {
let blob = new Blob([data], {type});
let url = window.URL.createObjectURL(blob);
downloadURI(url, name);
window.URL.revokeObjectURL(url);
}
I don't know if the question is just too old, but setting window.location to a download url will work, as long as the download mime type is correct (for example a zip archive).
var download = function(downloadURL) {
location = downloadURL;
});
download('http://example.com/archive.zip'); //correct usage
download('http://example.com/page.html'); //DON'T
Firefox and Chrome tested:
var link = document.createElement('a');
link.download = 'fileName.ext'
link.href = 'http://down.serv/file.ext';
// Because firefox not executing the .click() well
// We need to create mouse event initialization.
var clickEvent = document.createEvent("MouseEvent");
clickEvent.initEvent("click", true, true);
link.dispatchEvent(clickEvent);
This is actually the "chrome" way solution for firefox (I am not tested it on other browsers, so please leave comments about the compilability)