aderaaij
11/12/2017 - 9:31 PM

ES6 - Sanitize with tagged template string

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>