Trusted Types and CSP

Trusted Types, the Sanitizer API and CSP Reporting

Policies themselves are in Content Security Policy, Sandboxing and Trusted Types and Sanitization and XSS Defence. When one fires, the page gets a securitypolicyviolation event (all engines) with effectiveDirective, blockedURI and a code sample. For server reports, send Reporting-Endpoints: csp="https://example.com/r" and add report-to csp to the policy.

Violation events for CSP and Trusted Types, and a configured setHTML()HTMLLive
<!doctype html>
<meta http-equiv="Content-Security-Policy"
  content="img-src 'self'; script-src 'unsafe-inline'; require-trusted-types-for 'script'">
<pre id="out" style="font: 14px/1.5 monospace; margin: 0"></pre>
<script>
  const say = (text) => { out.textContent += text + '\n'; };
  document.addEventListener('securitypolicyviolation',
    (e) => say(`${e.effectiveDirective}: ${e.blockedURI} ${e.sample}`));
  const box = document.createElement('div');
  box.append(Object.assign(new Image(), { src: 'https://tracker.example/pixel.gif' }));
  try { box.innerHTML = 'hi'; } catch (e) { say(`innerHTML: ${e.name}`); }
  box.setHTML('<p onclick="steal()">Nice <b>post</b> <u>really</u>',
    { sanitizer: { elements: ['p', 'b'] } });
  say(`setHTML: ${box.innerHTML}`);
</script>
Browser output of Listing 9.79
Browser output of 79

setHTML() (Sanitizer API: Chrome 146 1 , Firefox 148 555 , not Safari 10 ) is always XSS-safe, so Trusted Types allow it. An elements allow-list drops other elements with their text ("really" vanished) unless they are listed in replaceWithChildrenElements.