我有网页(基本上是名片),其标题是根据用户的输入创建的。为此,我计划使用简单的JS模板字符串,而不是一些模板引擎。(为此目的,我使用了press.js/node.js)
response.send(`
<html>
<head>
<title>${user_inputed_title_got_from_DB}</title>
<meta property="og:title" content="${some_more_user_content}" />
</head>
<body>
<script>
window.location.href="/business-card/${user_input_number}";
</script>
</body>
</html>`)
如何避免来自恶意用户的XSS注入?
发布于 2022-02-13 14:15:09
对于普通的HTML标记,this answer should suffice
function escapeHtml(unsafe)
{
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
但是,需要更小心地处理脚本标记中的重定向问题。一种常见的方法是将重定向放入属性中,该属性可以用上面的函数转义:
<script data-redir="/business-card/${escapeHtml(user_input_number)}">
window.location.href = document.currentScript.dataset.redir;
</script>
https://stackoverflow.com/questions/71101370
复制相似问题