Prevent DOM-based XSS with Trusted Types and Content Security Policy with report-uri
The CSP response header:
Content-Security-Policy: require-trusted-types-for 'script'; report-uri https://emory.has.report/report
Trusted Types with a custom policy
<script>
const escapePolicy = trustedTypes.createPolicy('escapePolicy', {
createHTML: string => string.replaceAll('<', '<'),
});
document.getElementById('prompt-html').onclick = function() {
const html = prompt('Enter any HTML', 'foo <strong>bar</strong>');
if (html) {
document.getElementById('html-me').innerHTML = escapePolicy.createHTML(html);
document.getElementById('xss-me').innerHTML = html;
}
}
</script>
Related specs & documents
- Trusted Types Editor's Draft
- Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types on web.dev
- Trusted Types API on MDN