You can use data:
URIs and give it a file name, while still downloading the text. Try this:
document.getElementById("download").onclick = function(){
var l = document.createElement("a");
l.href = "data:text/plain;charset=UTF-8," + document.getElementById("dload-txt").value;
l.setAttribute("download", document.getElementById("dload-fn").value);
l.click();
}
textarea { width: 200px; height: 75px }
input { width: 200px }
<textarea placeholder="Enter text to download" id="dload-txt"></textarea><br/>
<input placeholder="Enter file name to download as" id="dload-fn"/><br/><br/>
<button id="download">Download</button>
This works in most browsers.
What it does is get the necessary data from the textarea and input, create a link that has an href
to data:text/plain;UTF-8,<textarea data>
, and set the download
attribute with the name set by the <input>
element. Then click the link, which will download the text.
The only not-all-browser-compatible things here are:
data:
URIs for storing the data as a link. data: URIs on CanIUse
click()
function to click the link. HTMLElement.click() on CanIUse
download
attribute to signify a download. download attribute on CanIUse
So basically:
Does not work in IE
Does not work in Opera Mini
Does not work in very early versions of Firefox, Chrome, Safari, Opera, and iOS Safari
Otherwise, this works in all major browsers, and doesn't need any Blob
object.
Blob construction on CanIUse
Blob URLs on CanIUse