Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save or display long string in JavaScript

I'm using Mozilla Firefox's console to run some JavaScript on blog to make an organized dump of the posts on it, and store it as a string variable. The string contains about 5000 messages, so it is quite long. I want to somehow save this string on my computer; this part may be done outside using methods outside of JavaScript.

The following options come to mind:

  1. Save the string as a txt file.
  2. Save the contents of the string to the clipboard, paste it in Notepad, then save it.
  3. Use the console's output and copy it from there.
  4. Show an alert, then copy it from there.
  5. Create a new HTML page with the string as the body and show it in a new window, then copy it from there.

However, I don't know how to do 1 and 2 in JavaScript, the string is too long for options 3 and 4 (3 complains about the string being too large when I expand it, 4 gets truncated), and I don't know how to do 5.

Any suggestions? Thank you in advance.

like image 879
RPFeltz Avatar asked Apr 04 '14 20:04

RPFeltz


2 Answers

I don't know about Firefox's console, but Chrome's console exposes a copy() method that will put strings of any size on your clipboard

like image 187
The Mighty Chris Avatar answered Sep 22 '22 18:09

The Mighty Chris


What you can do is the use the new HTML5 "download" attribute of an a tag. If you set the attribute to a file name, when clicked, instead of going to the file, it will download it with the file name. How does this help? Well, you can also use the 'data' scheme. If you have this:

<a href="data:text/plain,This is an example message." download="example.txt">click to download</a>

It will cause the file to download. If you use JavaScript to create the a tag, hide it, set the href to "data:text/plain,YourString", and download to "blogDump.txt", then use the click method, it will cause it to download.

EDIT: Example!

var link = document.createElement('a');
link.setAttribute('href', 'data:text/plain,Example');
link.setAttribute('download', 'example.txt');
link.click();

EDIT 2: FireFox doesn't like links that aren't in the DOM being clicked. Second example:

var link = document.createElement('a');
link.setAttribute('href', 'data:text/plain,Example');
link.setAttribute('download', 'example.txt');
document.getElementsByTagName("body")[0].appendChild(link).click();
like image 27
LuaWeaver Avatar answered Sep 22 '22 18:09

LuaWeaver