Solution 1 :

<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

Solution 2 :

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>

Problem :

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.

Comments

Comment posted by Godwin

for that you should pass them as query parameter like blah.com?text=hello and get them in the next page

Comment posted by Godwin

if it works mark this as right answer and up vote it as per

Comment posted by Elliot Harrell

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.

Comment posted by Godwin

@KwilverBear your question is answered , if it works please mark this as right answer and up vote it as per

Comment posted by Godwin

ask for new question if you need answers for new one……Please check the updated answer

By