You can use data:
URIs and give it a file name, while still downloading the text. Try this:
document.getElementById("dload").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;}
<!DOCTYPE html>
<html>
<head>
<title>Download File</title>
<meta charset="UTF-8"/>
</head>
<body>
<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="dload">Download</button>
</body>
</html>
This works in most browsers.
What it does is get the <textarea>
and <input>
tags that contain the necessary data, create a link that has an href
to data:text/plain;UTF-8,<textarea data>
, and set a download attribute with the name set by the <input>
tag. Then click the link, which will download the text.
The only not-all-browser-compatible things here are:
data:
URIs for having the data to download as a downloadable link. Click here for CanIUse browser compatability tables
click()
function to click the link. Click here for CanIUse browser compatability tables
download
attribute to signify a download. Click here for CanIUse browser compatability
So basically:
Does not work in IE
Does not work in Opera Mini
Does not work in 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 Constructing CanIUse compatibility tables
Blob URL CanIUse compatibility tables