Reputation: 82
I am attempting to put together a function that works in the browser to:
©
to ©
) but not replace characters critical to HTML ( < > / " ' # . etc.)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, '©');
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
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, '©');
// 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