You can define an anchor element, <a>
, using URL encoding to generate your TXT file and download it. You only need to dynamically create the element, set the href
attribute and the download
property to the name of the file you want to create; after you insert it into the body of the page - some browsers can block the click
event if the element is not in the body of the page - and trigger the click
event of the element, 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);
}
See 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>