Trusted Types API: 锁定 DOM API
的不安全部分,以防止客户端跨站脚本(XSS
)攻击
<!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>
<!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 = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
};
const policy = trustedTypes.createPolicy('myPolicy', {
createHTML: (input) => input.replace(/[&<>"'\/]/g, (char) => entityMap[char]),
});
const trustedHTML = policy.createHTML(strHTML);
content.innerHTML = trustedHTML;
</script>
</body>
</html>