Drew Albinson
Drew Albinson

Reputation: 82

Javascript: Convert HTML Entities then Download HTML

I am attempting to put together a function that works in the browser to:

  1. Take the HTML within an element
  2. Replace common special characters with HTML entities (i.e. convert © to &copy;) but not replace characters critical to HTML ( < > / " ' # . etc.)
  3. Download the replaced HTML as a file, or even better yet copy that code to the clipboard

I have been able to get the following to work for points 1 and 3, but the replace function doesn't seem to work on characters within nested HTML elements. I'm not very advanced at javascript and haven't been able to track down a solution for this. Any help is appreciated.

<div id="email-html">
  <p>test ©</p>
</div>

<a id="ClickMe" onclick="(function () {
    function downloadInnerHtml(filename, elId, mimeType) {
        var elHtml = document.getElementById(elId).innerHTML;
        var link = document.createElement('a');
        var coHtml = elHtml.replace(/©/g, '&copy;');
        mimeType = mimeType || 'text/plain';

        link.setAttribute('download', filename);
        link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(coHtml));
        link.click();
    }

    var fileName = 'email.html';
    downloadInnerHtml(fileName, 'email-html', 'text/html');
})();
" href="#">Click to Download</a>

Upvotes: 0

Views: 133

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65808

By reorganizing your code to eliminate inline JavaScript and follow modern web standards. It works:

// Place this in a <script> tag that comes just before the closing body tag (</body>)

// Get a reference to the hyperlink
var a = document.getElementById("clickMe");

// Set up a click event handler for the hyperlink
// Because the handler needs arguments passed to it, wrap it 
// within another function that will call the actual handler and pass
// those arguments
a.addEventListener("click", function () {
  var fileName = 'email.html';
  downloadInnerHtml(fileName, 'email-html', 'text/html');
});

function downloadInnerHtml(filename, elId, mimeType) {
        // Better to use textContent instead of innerHTML here
        var elHtml = document.getElementById(elId).textContent;
        var link = document.createElement('a');
        var coHtml = elHtml.replace(/©/g, '&copy;');
        
        // Test to see the replaced content
        console.log(coHtml);
        
        // Commented as it is not relevant to the issue
        //mimeType = mimeType || 'text/plain';

        //link.setAttribute('download', filename);
        //link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(coHtml));
        //link.click();
}
<div id="email-html">
  <p>test ©</p>
</div>

<a id="clickMe" href="#">Click to Download</a>

Upvotes: 1

Related Questions