【发布时间】:2026-01-28 16:45:01
【问题描述】:
为了保护 xss 攻击,我尝试使用以下函数对要显示给用户的每条消息进行编码。
function encodeRFC5987ValueChars(str)
{
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
}
示例输入消息如下所示
Start 20 TV's test; star ;; '' -- testagain., comma. </>
我从这个函数收到的输出消息如下所示。
Start%2020%20TV%27s%20test%3B%20star%20%3B%3B%20%27%27%20--%20testagain.%2C%20comma.%20%3C%2F%3E
我尝试显示如下。
document.getElementById("labelResult").innerHTML = "Start%2020%20TV%27s%20test%3B%20star%20%3B%3B%20%27%27%20--%20testagain.%2C%20comma.%20%3C%2F%3E";
一切正常,但用户可读性非常差。
我需要解码吗?如果我解码了,那我怕会导致xss攻击?
请有任何建议。
【问题讨论】:
-
我不会使用
encodeURIComponent来转义字符串,它会替换的东西的数量是超级大材小用。看看这个问题/答案:*.com/questions/6234773/…
标签: javascript xss decode encode