You can define an anchor element, <a>
, using the URL encoding to generate your TXT file and download it. Just create the element dynamically, set the attribute href
and the property download
with the name of the file you want to create; after you insert it into the body of the page - some browsers may block the event click
if the element is not in the body of the page - and trigger the event click
of the element by removing it from the body of the page at the end.
function createAndDownload(filename, text) {
const 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);
}
Take an example:
function createAndDownload(filename, text) {
const 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);
}
<button onClick="createAndDownload('sopt.txt', 'Stack Overflow em Português')">Download</button>
This might help you if you know English in this case: https://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery
– Alexsander Camargo