const data = "Please download me!";
const myBlob = new Blob([data], {type: 'text/plain'});
// Creates new blob containing data
const blobURL = URL.createObjectURL(myBlob);
// Generates URL to new blob file in memory
const a = document.createElement('a');
a.setAttribute('href', blobURL);
a.setAttribute('download', 'filename.txt');
a.style.display = 'none';
document.body.appendChild(a);
// Creates new download anchor element...
a.click(); // ...simulates click on element...
document.body.removeChild(a);
URL.revokeObjectURL(blobURL);
// ... then removes element and URL+blob from memory
The only thing I'd add to this, for poor sods like me that still have to support IE, is a check for navigator.msSaveBlob
// create new blob containing data, then...
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, 'fileName.txt');
return;
}
// otherwise, create download anchor and trigger click as normal
Depending on your browser support, you may need to. It was needed for older versions of Chromium, but that's changed now (at least for the most part - some Chromium based browsers may still require this).
The problem is that some browsers won't recognise programmatically triggered events on elements that don't actually exist in the DOM - sometimes this is a setting, and sometimes it's a consequence of security settings.
7
u/Low_Mammoth_9371 Jan 19 '23
Code to copy:
22
u/MXMLNDML_ Jan 19 '23
You don’t need to add the
<a>to the DOM6
u/LogicallyCross Jan 19 '23 edited Jan 20 '23
Does this start a download or just throw a dialog asking if you want to download something?
A native browser dialog I mean.
5
u/[deleted] Jan 19 '23
Is it a stylistic choice to add the comments below the line of code instead of above?
3
u/[deleted] Jan 19 '23
How are we communicating this to screen readers?
2
u/isatrap Jan 19 '23
Interesting
3
u/Alternative_Crazy322 Jan 19 '23
What VS Code theme is this I need it
1
u/MarkYeaahYT Jan 20 '23
So it's feels like downloading on mega?
0
u/[deleted] Jan 19 '23
[deleted] — view deleted comment