Another way to do it would be to use a Blob
and URL.createObjectURL
. All recent browsers including Safari 6+ support them.
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea
.
Another thing to note about the example is that I used the download
attribute on the download link. Unfortunately, Safari does not currently support it. However in browsers that do, the file will automatically be downloaded when clicked instead of opening the file in the browser. Also, since I set the download
attribute to info.txt
the file will be downloaded with that name instead of the random name generated by createObjectURL
.