Created
April 24, 2014 17:46
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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(); |
In the network tab of the dev tool, this URL fails: //pagead2.googlesyndication.com/pagead/adsbygoogle.js It triggers a .txt file download. –
Anyone, please help me ....My Link
Don't forget to revoke the object URL to free the memory - they don't get garbage collected
does not work for me....
but this worked:
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
download("hello.txt","This is the content of my file :)");
Great! It worked with Google Chrome 78.0.3904.97.
Thank you so much!
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
thanks is a great solution