Created
March 20, 2020 09:41
-
-
Save mousetail/0b45eedb40adb2edc9ca18ec4a806a60 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const allowedNodeTypes = [ | |
'p', | |
'span', | |
'div', | |
'a', | |
'img', | |
'h1', | |
'h2', | |
'h3', | |
'h4', | |
'h5', | |
'strong', | |
'b', | |
'em', | |
'pre', | |
'blockquote', | |
'table', | |
'tr', | |
'td', | |
'tbody', | |
'u', | |
'br', | |
'i', | |
'ul', | |
'ol', | |
'li', | |
'figure', | |
'code', | |
'hr', | |
'italic', | |
'font', | |
'sup', | |
'sub' | |
] | |
const allowedAttributeTypes = [ | |
'style', | |
'href', | |
'src', | |
'alt', | |
'title' | |
] | |
const urlTransformAttributeTypes = [ | |
'src', | |
'href' | |
] | |
function recursivelyCopyContent(elem1, elem2, keep_tags) { | |
while (elem2.firstChild){ | |
elem2.removeChild(elem2.firstChild); | |
} | |
if (keep_tags === undefined) { | |
keep_tags = true; | |
} | |
elem1.childNodes.forEach(child=>{ | |
//console.log(child); | |
if (child.nodeType === Node.TEXT_NODE){ | |
elem2.appendChild( | |
document.createTextNode(child.data) | |
); | |
} | |
else if (child.nodeType === Node.ELEMENT_NODE) { | |
let tag = child.tagName.toLowerCase(); | |
if (allowedNodeTypes.indexOf(tag)>=0){ | |
let element = document.createElement(keep_tags?tag:'span'); | |
if (keep_tags){ | |
for (var name of child.attributes){ | |
if (urlTransformAttributeTypes.indexOf(name.nodeName)>=0){ | |
element.setAttribute(name.nodeName, new URL(name.value, 'https://thedailywtf.com/articles/')); | |
} | |
else if (allowedAttributeTypes.indexOf(name.nodeName)>=0){ | |
element.setAttribute(name.nodeName, name.value); | |
} else { | |
console.log("not alled attribute", name.nodeName); | |
} | |
} | |
} | |
recursivelyCopyContent(child, element); | |
elem2.appendChild(element); | |
} else { | |
console.log("Not allowed", tag); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment