-2

I'm working on a project that randomly generates a set of characters intended to be used for a password and want the user to be able to download the results as a text file. I've read some things on BLOBs and a few other methods that haven't worked. It'd be a big help if someone could offer a method that works.

TL;DR: Need a way to download text from an HTML textarea as a .txt file using JS

McSquidy
  • 19
  • 5
  • 1
    Does this answer your question? [Download textarea contents as a file using only Javascript (no server-side)](https://stackoverflow.com/questions/609530/download-textarea-contents-as-a-file-using-only-javascript-no-server-side) – Dave Feb 03 '22 at 16:24
  • I'll test it out and get back to you – McSquidy Feb 03 '22 at 16:26
  • @Dave trying to download using the method you linked returns an error in the console stating, "ReferenceError: t is not defined at HTMLButtonElement.onclick (/:70:79)" Perhaps it's because I'm on Opera GX instead of Fire Fox or Chrome, though – McSquidy Feb 04 '22 at 17:20

1 Answers1

1

You should be able to programmatically create a link that uses a data url with your text, add a download attribute so the browser downloads instead of navigating (and to specify a filename), and click it.

This doesn't run as a SO snippet, presumably for security reasons, but it should work out in the world (and you can copy/paste this in your dev tools console to test it):

const generatedText = 'some generated blob of text';

// create an anchor element that we can programmatically click
const a = document.createElement('a');

// set up a data uri with the text
a.href = `data:text/plain,${generatedText}`;

// set the download attribute so it downloads and uses this as a filename
a.download = 'the-name-of-the-file.txt';

// stick it in the document
document.body.appendChild(a);

// click it
a.click();
ray
  • 26,557
  • 5
  • 28
  • 27