Trusted Types API

_clai發表於2024-04-30

Trusted Types API: 鎖定 DOM API 的不安全部分,以防止客戶端跨站指令碼(XSS)攻擊


  • untrusted

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Trusted Types API</title>
  </head>
  <body>
    <strong>Trusted Types API</strong>
    <hr />
    <div class="content"></div>

    <script>
      const content = document.querySelector('.content');

      const strHTML = `<div>
        <p>This is a trusted string.</p>
        <img src="https://via.placeholder.com/350x150" alt="placeholder image" />
      </div>`;

      content.innerHTML = strHTML;
    </script>
  </body>
</html>

  • trusted

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Trusted Types API</title>
  </head>
  <body>
    <strong>Trusted Types API</strong>
    <hr />
    <div class="content"></div>

    <script>
      const content = document.querySelector('.content');

      const strHTML = `<div>
        <p>This is a trusted string.</p>
        <img src="https://via.placeholder.com/350x150" alt="placeholder image" />
      </div>`;

      const entityMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;',
        '/': '&#x2F;',
      };
      const escapedStrHTML = trustedTypes.createPolicy('myPolicy', {
        createHTML: (input) => input.replace(/[&<>"'\/]/g, (char) => entityMap[char]),
      });

      const trustedHTML = escapedStrHTML.createHTML(strHTML);
      content.innerHTML = trustedHTML;
    </script>
  </body>
</html>

相關文章