JavaScript - Download frontend file without server
Sometimes you have string in the browser web page you want to download. You can make the string downloadable.
const makeDownload = function(val, filename, contentType) {
if (!val || !filename || !contentType) {
return false;
}
const a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([val], {type: contentType}));
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
return true;
};
To call the function, pass in the data to download, filename, and content type.
makeDownload(
"First name,Last name,Email\nJohn,Doe,[email protected]\nJane,Doe,[email protected]",
"filename.csv",
"text/csv"
);
Here is an example adding a listener to buttons.
<input type="button" class="download" data-content="Hello World!" value="Download" />
document.querySelector("input[type=\"button\"].download").addEventListener("click", function(e) {
makeDownload(this.getAttribute("data-content"), "filename.txt", "text/plain");
});