Trusted Types API

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 policy = trustedTypes.createPolicy('myPolicy', {
        createHTML: (input) => input.replace(/[&<>"'\/]/g, (char) => entityMap[char]),
      });

      const trustedHTML = policy.createHTML(strHTML);
      content.innerHTML = trustedHTML;
    </script>
  </body>
</html>
posted @ 2024-04-30 23:06  _clai  阅读(6)  评论(0编辑  收藏  举报