Skip to content

Instantly share code, notes, and snippets.

@xcambar
Last active September 3, 2018 09:42
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 xcambar/0b972a5d5834fecdb958324de08023fe to your computer and use it in GitHub Desktop.
Save xcambar/0b972a5d5834fecdb958324de08023fe to your computer and use it in GitHub Desktop.
Efficiently and securely remove <script> tags from source HTML
// This code would normally inject global variables and run an alert
// if injected in your document naively
const source = '<p>bla <script>window.SHIT=true</script></p><script>alert("SHIT")</script>'
// Crete a DocumentFragment from the source HTML
const frag = document.createRange().createContextualFragment(source)
// Remove all the <script> nodes
[...frag.querySelectorAll('script')].forEach((e)=> {
e.parentNode.removeChild(e)
})
// Rebuils a clean source HTML
// We use reduce and concat here because there's no proper API to do this
const cleanHTML = [...frag.childNodes].reduce((m, e)=> {
return m + (e.outerHTML || e.textContent)
}, '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment