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 = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
};
const escapedStrHTML = trustedTypes.createPolicy('myPolicy', {
createHTML: (input) => input.replace(/[&<>"'\/]/g, (char) => entityMap[char]),
});
const trustedHTML = escapedStrHTML.createHTML(strHTML);
content.innerHTML = trustedHTML;
</script>
</body>
</html>
标签:const,content,strHTML,API,Types,Trusted
From: https://www.cnblogs.com/chlai/p/18168859