Search code examples
javascriptconcatenationcreateelement

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"?


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.