背景与价值URL片段常用于前端路由与状态传递,需校验与转义以防DOM-Based XSS与污染。统一规范白名单与长度:仅允许指定片段并限制长度与字符集。去污染:剔除危险字符与编码异常。受控更新:仅使用textContent或转义后写入。核心实现白名单与去污染const allowHash = new Map<string, { maxLen: number; re: RegExp }>([

['msg', { maxLen: 64, re: /^[A-Za-z0-9_\- ]+$/ }],

['tab', { maxLen: 16, re: /^[A-Za-z0-9_\-]+$/ }]

])

function parseHash(): Record<string, string> {

const h = (location.hash || '').replace(/^#/, '')

const out: Record<string, string> = {}

for (const part of h.split('&')) {

if (!part) continue

const [k, v] = part.split('=')

const rule = allowHash.get(k)

if (!rule) continue

const val = decodeURIComponent(v || '')

if (val.length > rule.maxLen) continue

if (!rule.re.test(val)) continue

out[k] = val

}

return out

}

受控更新function updateDom(el: Element, s: string) { el.textContent = s }

落地建议对hash参数采用键值对约定并进行白名单校验;写入DOM使用textContent。验证清单hash是否按白名单解析与校验;DOM更新是否使用受控写入。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部