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

如何防范Cross site scripting: DOM?URL数据验证方案咨询

防范DOM型XSS的修复方案

你的代码直接把用户可控的path和document.location.search拼接到新URL中,存在DOM型XSS风险——攻击者可以构造恶意路径或查询参数,注入脚本代码。以下是落地的防护方法:

1. 对白名单内的内容做严格验证

startat参数应该指向合法的站内页面,给path设置明确的格式规则,只允许符合要求的文件名,不符合就用默认值:

var path = document.location.pathname;
if (path.lastIndexOf("/") !== 0) {
  path = path.substring(path.lastIndexOf("/") + 1);
}
// 验证规则:只能是字母、数字、下划线,后缀为2-4位的合法扩展名(如htm、html)
const validFileName = /^[a-zA-Z0-9_]+\.[a-zA-Z0-9]{2,4}$/;
if (!validFileName.test(path)) {
  path = "default.htm"; // 不符合规则就用默认页面
}

2. 清理查询参数,只保留必要字段

document.location.search是用户可控的,不能直接拼接。只保留业务需要的参数,过滤掉无关或恶意参数:

// 假设业务只需要保留id、lang这两个参数
const allowedParams = ['id', 'lang'];
const rawParams = new URLSearchParams(document.location.search);
const cleanParams = new URLSearchParams();

allowedParams.forEach(param => {
  if (rawParams.has(param)) {
    cleanParams.append(param, rawParams.get(param));
  }
});
// 生成清理后的查询字符串
const cleanSearch = cleanParams.toString() ? `?${cleanParams.toString()}` : '';

3. 对参数值做URL编码

即使验证通过,也要用encodeURIComponent对path编码,避免特殊字符破坏URL结构,进一步降低注入风险:

const encodedPath = encodeURIComponent(path);
open(`default.htm?startat=${encodedPath}${cleanSearch}`, "_top");

核心原则

别用黑名单过滤(比如试图去掉<script>这类标签),黑名单永远有漏网之鱼。白名单验证+URL编码是最可靠的防护方式——只允许已知合法的内容,其他全部拦截或替换为默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:45:40