Reputation: 4093
I'm trying to set up an export function in JavaScript for a packaged web app that turns a string stored in localStorage into a plain text file for downloading. As JavaScript does not have access to the computer's file-system, I'd like to set it up so that it create a blank text file (or, failing that, a simple HTML page) and open in in the web-browser; as it wouldn't be accessing any file-systems I was hoping this would be possible.
I was thinking of using a Data URI scheme to open the localStorage as plain text, such as the following:
function exportFile() {
window.open("data:text/plain;charset=utf-8," + localStorage.WebAppData);
};
But it's much slower than I expected, which I guess is because it's sticking the whole document in the URL box. Though probably not an issue with the code, some web browsers, like Google Chrome, won't let me save the resulting file. (And for some reason all the line-breaks have turned into spaces....)
Any suggestions to fix these problems or better ways of doing a similar function will be greatly appreciated!
Upvotes: 4
Views: 4151
Reputation: 111
In order to retain line-breaks in the data exported with window.open you may wrap up your data with encodeURI:
var data1 = "Line \n break. And \r\n another one";
window.open("data:application/octet-stream, " + encodeURI(data1));
Otherwise you may export your data encoded in base64 with the btoa function:
var data1 = "Line \n break. And \r\n another one";
window.open("data:application/octet-stream;base64, " + btoa(data1));
Upvotes: 1
Reputation: 2213
Not really a solution, rather a work-around, but your question and the answer by @Mic lead me down this route:
Just use data:text/html
as then you can put in line breaks using <br />
text/plain
but couldn't get them to show up. document.write()
and document.body.textContent()
, etc also suffer from the same problem. Line breaks just get ignored.text/plain
over text/html
EDIT: This approach works in Chrome, but not Firefox
win = window.open("", "win")
win.document.body.innerText = "Line \n breaks?"
Have to use innerText
though. InnerHTML
or textContent
remove the line breaks. This works on both:
win = window.open("", "win")
win.document.body.innerHTML = "<pre>Line \n breaks?</pre>"
So perhaps you could just wrap everything in <pre>
tags? Although I guess both of these have the same "problem" as the `
suggestion in that it's actually creating a HTML document rather than a text/plain one.
Upvotes: 0
Reputation: 25164
Did you try something like:
window.open("data:text/plain;charset=utf-8," + localStorage.WebAppData);
For the download, I guess you need a round trip to a server, that will set a mime/type that will make the download box to pop up.
EDIT:
If you use localStorage
, may be window.postMessage
is available in your environment and could help for speed.
Upvotes: 2