Saving a generated file
a Blob object URL on a download link
Chrome38
Edge79
Firefox28
Safari10.1
Features it needs
file-saver was written when saving a blob meant branching across engines, including an msSaveBlob path for old IE and Edge. What is left once those are gone is four lines: make a Blob, turn it into an object URL, click a link carrying the download attribute, then revoke the URL. The attribute also supplies the filename, which is the part people usually reach for the library to get.
When this applies
Offering a file the page generated for the user to save.
The native approach
function save(blob, filename) {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
link.click();
// Revoke, or the blob is held in memory until the document goes. Deferred
// rather than immediate: revoking in the same task cancels the save in
// some engines, because the fetch behind the download has not started.
setTimeout(() => URL.revokeObjectURL(url), 0);
}
save(new Blob([csv], { type: "text/csv" }), "report.csv");When the dependency is still right
An answer that always says "the platform covers it" is worse than no answer. These are the cases where this one does not hold.
- The file is larger than memory allows. A Blob is held in memory, so streaming a big export to disk needs the File System Access API, which is not Baseline.
- The link points at another origin. The download attribute is ignored cross-origin, so the browser navigates to the file instead of saving it, and object URLs are same-origin so this only applies when the href is a remote one.
- You run inside a WebView or an in-app browser that ignores the attribute. Several do, and the library's fallbacks are what papers over that.
- You support browsers below Chrome 14, Firefox 20 or Safari 10.1. Safari supported the attribute considerably later than the others.
Signs it was hand-rolled
No package is involved in any of these, so nothing would match in a package.json. If the code looks like one of them, this rule applies anyway, and the conditions above still decide.
- a data: URI assigned to window.location to trigger a save, which truncates on larger files
- a hidden iframe or form submitted to make the browser treat a response as a download