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 escapedStrHTML = trustedTypes.createPolicy('myPolicy', {
createHTML: (input) => input.replace(/[&<>"'\/]/g, (char) => entityMap[char]),
});
const trustedHTML = escapedStrHTML.createHTML(strHTML);
content.innerHTML = trustedHTML;
</script>
</body>
</html>