Last active
November 13, 2017 14:12
-
-
Save aderaaij/0955cb946ab516d4c7d4e680cadad9b5 to your computer and use it in GitHub Desktop.
A way to sanitize html with DOMPurify and tagged template strings. Remember not to rely on just client-side scripting to do things like this. From es6.io
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Tagged Templates</title> | |
<style> | |
abbr { | |
border-bottom:1px dotted grey; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="bio"> | |
</div> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/0.8.2/purify.min.js"></script> | |
<script> | |
function sanitize(strings, ...values) { | |
const dirty = strings.reduce((prev, next, i) => `${prev}${next}${values[i] || ''}`, ''); | |
return DOMPurify.sanitize(dirty); | |
} | |
const first = 'Wes'; | |
const aboutMe = `I love to do evil <img src="http://unsplash.it/100/100?random" onload="alert('you got hacked');" />`; | |
const html = sanitize` | |
<h3>${first}</h3> | |
<p>${aboutMe}</p> | |
`; | |
const bio = document.querySelector('.bio'); | |
bio.innerHTML = html; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment