You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入值含<script>代码时,Dom文本转HTML是否需防范XSS?

关于XSS风险的疑问:场景1是否需要防范?

背景

现有HTML输入框#bc_hare_status_inp的value值为<script>alert('hi')</script>,该值来自数据库存储的脚本代码。

场景1

代码示例:

var caseStatus = $("#bc_hare_status_inp").val();
rp_html = `<input type="text" value="${hareStatus}" style="width:250px">`
$('select[name="hare_status"]').replaceWith(rp_html);

现象:生成的新input中脚本无法执行,但CodeQL提示“Dom text reinterpreted as HTML”

场景2

代码示例:

var hareStatus = $("#bc_hare_status_inp").val();
rp_html = `${hareStatus}`
$('select[name="hare_status"]').replaceWith(rp_html);

现象:脚本会执行,符合“Dom text reinterpreted as HTML”的XSS风险提示

疑问

场景2需防范XSS攻击已明确,场景1是否也需采取防范措施?


回答

场景1必须做防范,别因为当前测试的脚本没执行就掉以轻心。

虽然<script>alert('hi')</script>作为input的value不会触发执行,但攻击者换个payload就不一样了——比如用" onmouseover="alert('xss')" 这种内容,拼到HTML里后会变成:

<input type="text" value="" onmouseover="alert('xss')" " style="width:250px">

用户只要鼠标移到这个输入框上,就会触发弹窗,这属于属性型XSS,同样能造成安全问题。

CodeQL的提示不是误报,因为你是把用户可控的内容直接拼进HTML字符串,这种写法本身就存在注入风险。不管当前的payload有没有效果,只要有注入的可能,就必须做防护。

正确的做法是放弃字符串拼接生成HTML,改用jQuery的DOM创建方法,比如:

var hareStatus = $("#bc_hare_status_inp").val();
var newInput = $('<input>', {
  type: 'text',
  value: hareStatus,
  style: 'width:250px'
});
$('select[name="hare_status"]').replaceWith(newInput);

这种方式下jQuery会自动对value值做转义处理,从根源上杜绝XSS风险。


内容的提问来源于stack exchange,提问作者Santhosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 02:17:40