<textarea id="text-val" rows="4" style="height: 80%;width: 90%;"></textarea><br/><br/>
<input type="button" id="dwn-btn" value="Save" />
<script>
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function() {
var text = document.getElementById("text-val").value;
var filename = "example.html";
download(filename, text);
}, false);
</script>
I hope this is what you are expecting
Create new Blob
from your html script with application/octet-stream
mime type. Then use URL.createOjectURL
api to generate download link. And navigate to that link. In this example code I navigated using creating temporary link (<a>
) element.
function download() {
var blobPart = ['<h1>Test</h1>'];
var blob = new Blob(blobPart, {
type: "application/octet-stream"
});
var urlObj = URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.href = urlObj;
a.download = 'filename.html';
a.click();
a.remove();
}
document.getElementById('download-btn').addEventListener('click', download);
<a href="#" id="download-btn">Download</a>
I’m looking for a way to add a download feature to my JS that will create a file using the programming that a user might enter in, lets say, a <textarea>
. Are there any features in JS that would work similar to this? (HTML Format!!)
var x = document.write("<p>Hi!</p>");
window.replace(x);
And then:
<button onclick="open()">Save</button>
<script>
var hi = document.write("<p>hi</p>;");
open() {
window.open(hi)
}
</script>
After they opened the variable on the new page, the user could use ctrl + s to save the page displayed. Ideas?
Thanks in advance.
for that you should pass them as query parameter like blah.com?text=hello and get them in the next page
That is a great idea. I understand, and it would work, but I just now realized that the code would save as the code, and not save the var that I wanted to. Please look at my updated question for more on what I was thinking.
@KwilverBear your question is answered , if it works please mark this as right answer and up vote it as per
ask for new question if you need answers for new one……Please check the updated answer