Skip to content

Instantly share code, notes, and snippets.

@Yaffle
Last active December 25, 2015 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yaffle/7007789 to your computer and use it in GitHub Desktop.
Save Yaffle/7007789 to your computer and use it in GitHub Desktop.
markup.doc = document.implementation.createHTMLDocument ? document.implementation.createHTMLDocument("") : null;
function markup(s) {
var doc = markup.doc;
var div = null;
if (doc === null) {
div = document.createElement("div");
if (window.toStaticHTML) {// IE 8
div.innerHTML = window.toStaticHTML(s);
} else {
div.appendChild(document.createTextNode(s));
}
} else {
div = doc.createElement("div");
div.innerHTML = s;
}
var whiteList = ["A", "ABBR", "ADDRESS", "ARTICLE", "ASIDE", "B", "BDO", "BLOCKQUOTE", "BR", "CAPTION", "CITE", "CODE", "COLGROUP", "DATA", "DD", "DEL", "DFN", "DIV", "DL", "DT", "EM", "FIGCAPTION", "FIGURE", "H1", "H2", "H3", "H4", "H5", "H6", "HR", "I", "INS", "KBD", "LI", "MARK", "NAV", "OL", "P", "PRE", "Q", "RP", "RT", "RUBY", "S", "SAMP", "SECTION", "SMALL", "SPAN", "STRONG", "SUB", "SUP", "TABLE", "TBODY", "TD", "TFOOT", "TH", "THEAD", "TIME", "TR", "U", "UL", "VAR", "WBR"];
var attributesWhiteList = ["title"];
var attributesToRemove = [];
var walk = function (element) {
var child = element.firstChild;
while (child !== null) {
var next = child.nextSibling;
var nodeType = child.nodeType;
var allowElement = true;
if (nodeType !== Node.TEXT_NODE) {
if (nodeType === Node.ELEMENT_NODE) {
var tagName = child.tagName;
var allowElement = whiteList.indexOf(tagName) !== -1;
var allowedAttributes = attributesWhiteList;
if (tagName === "A") {
if (/^(data|blob|javascript)\:$/i.test(child.protocol)) {
allowElement = false;
}
allowedAttributes = ["href", "title"];
}
if (allowElement) {
var attributes = child.attributes;
var i = attributes.length;
while (--i >= 0) {
var attribute = attributes[i];
var name = attribute.name;
if (allowedAttributes.indexOf(name) === -1) {//TODO: indexOf
attributesToRemove.push(name);
}
}
i = attributesToRemove.length;
while (--i >= 0) {
child.removeAttribute(attributesToRemove[i]);
}
attributesToRemove.length = 0;
}
if (allowElement) {
walk(child);
}
} else {
allowElement = false;
}
} else {
var span = document.createElement("span");
span.innerHTML = autoLink(child.nodeValue);
element.replaceChild(span, child);
}
if (!allowElement) {
element.removeChild(child);
}
child = next;
}
};
walk(div);
return div;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment