htmlEnc / htmlDec
Uses document.implementation.createHTMLDocument to ensure <script> safety and no resource fetching.
by sstur
JavaScript
var doc;
function htmlEnc(text) {
if (!doc) {
doc = document.implementation.createHTMLDocument('x');
}
doc.body.appendChild(doc.createTextNode(text));
var html = doc.body.innerHTML;
doc.body.removeChild(doc.body.firstChild);
return html;
}
function htmlDec(html) {
if (!doc) {
doc = document.implementation.createHTMLDocument('x');
}
doc.body.innerHTML = html;
var text = doc.body.textContent;
while (doc.body.firstChild) {
doc.body.removeChild(doc.body.firstChild);
}
return text;
}
console.log(htmlEnc('a > b'));
console.log(htmlDec('a > b'));