Skip to content

Instantly share code, notes, and snippets.

@aderaaij
Last active November 13, 2017 14:12
Show Gist options
  • Save aderaaij/0955cb946ab516d4c7d4e680cadad9b5 to your computer and use it in GitHub Desktop.
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
<!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