Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why aren't my downloaded HTML file displaying as HTML?

Obligatory; I’ve been away from HTML for a long time and have never really played with javascript seriously.
But now I’m trying to make a document that is ment to be opened locally and save "a copy of itself".

<html>
<body>
    <textarea id="inputText" cols=100% rows=20></textarea>
    <button onclick="save()" type="button" id="save">Save Changes</button>
</body>
<script>
    function save() {
        var a = document.createElement("a");
        var breaky = "&lt;br&gt;"
        var string1 = "&lt;textarea id=&quot;inputText&quot; cols=100% rows=20&gt;"
        var string2 = document.getElementById("inputText").value
        a.href = window.URL.createObjectURL(new Blob([breaky.concat(string1,string2,"&lt;/textarea&gt;",breaky)], {type: "text/plain"}));
        a.download = "demo.html";
        a.click();
    }   
</script>
</html>

When I open demo.html it just displays "<br><textarea id="inputText" cols=100% rows=20></textarea><br>" as plain text and I can’t figure out why.

Also… is there a better way of joining strings. I tried just using a + but I couldn’t get it to work when joining a var and a "string"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is, that you "encode" the lesserthan and greaterthan signs. Your output HTML is literally &lt;br&gt;&lt;textarea id=&quot;inputText&quot;....

You don’t have to convert these chars to their HTML entity:

<html>
<body>
    <textarea id="inputText" cols=100% rows=20></textarea>
    <button onclick="save()" type="button" id="save">Save Changes</button>
</body>
<script>
    function save() {
        var a = document.createElement("a");
        var breaky = "<br>"
        var string1 = "<textarea id=\"inputText\" cols=100% rows=20>"
        var string2 = document.getElementById("inputText").value
        a.href = window.URL.createObjectURL(new Blob([string1+string2+"</textarea>"], {type: "text/plain"}));
        a.download = "demo.html";
        a.click();
    }   
</script>
</html>

And for the string joining you can use the plus sign as I did.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading