Search code examples
javascriptescapingdata-uri

How to ensure the body of a data: URI is correctly interpreted?


Okay for a little background I am creating an HTML email signature generator for a client and have run into an issue multiple times. I created a function that allows the user to download the file as a HTML so they may install it into their email platform of choice. The problem I am running into a lot is for some reason when using # anywhere in the HTML file it seems like the code stops there when downloading. I assume the # is somehow interfering with the .innerHTML; making it stop for some reason.

var content =
  "<p>J. Random Hacker " + 
  "<p>Chief Example Officer, Yoyodyne, Inc. " +
  "<p>We are the #1 widget manufacturer in the world!";
var a = document.createElement("a");
a.download = "signature.html";
a.href = "data:text/html," + content; // Grab the HTML
a.click(); // Trigger a click on the element

Also here is an image of how the code is cut off, you can see this in inspect element after you download the file. enter image description here


Solution

  • I have figured it out!!!! Thank you to those who have helped guide me! I did some research based on what I was told about the UTF-8 not allowing # symbols and that the # symbol fragments the URL. I ended up putting the "document.getElementById("content")" as a variable and then did "encodeURIComponent(content)". I am not 100% sure why it works but will find out. I assume it encodes it to where the # is no longer there until decoded back to # there for not fragmenting the URL.

    function download() { 
      var filename = document.getElementById("filename").value; 
      var content = document.getElementById("content").innerHTML; 
      var a = document.body.appendChild(document.createElement("a")); 
      a.download = filename + ".html"; 
      a.href = "data:text/html;charset=utf-8," + encodeURIComponent(content); 
      a.click(); // Trigger a click on the element
    }
    

    Thank you to those who help!

    Best,

    Andrew