Skip to content

Instantly share code, notes, and snippets.

@liabru
Created April 24, 2014 17:46
Show Gist options
  • Save liabru/11263260 to your computer and use it in GitHub Desktop.
Save liabru/11263260 to your computer and use it in GitHub Desktop.
Save a text file locally with a filename, by triggering a download in JavaScript
/*
* Save a text file locally with a filename by triggering a download
*/
var text = "hello world",
blob = new Blob([text], { type: 'text/plain' }),
anchor = document.createElement('a');
anchor.download = "hello.txt";
anchor.href = (window.webkitURL || window.URL).createObjectURL(blob);
anchor.dataset.downloadurl = ['text/plain', anchor.download, anchor.href].join(':');
anchor.click();
@wilyJ80
Copy link

wilyJ80 commented Sep 14, 2024

Also, browsers might block subsequent downloads because of security.
A solution is to probably stick with manually downloading through the element appended somewhere.

function appendDownloadableText(filename, string) {
    const data = new Blob([string]);
    const url = URL.createObjectURL(data);
    const a = document.createElement('a');

    a.href = url;
    a.download = filename;
    a.textContent = filename;
    document.body.appendChild(a);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment