
react防止xss攻击的方法:
react在渲染html内容和渲染dom属性时都会将 "'&<>这几个字符进行转义,转义部分源码如下:
for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '"'; break; case 38: // & escape = '&'; break; case 39: // ' escape = '''; break; case 60: // < escape = '<'; break; case 62: // > escape = '>'; break; default: continue; } }使用以上方法,恶意代码在渲染到html前都被转成了字符串,例如:
// 一段恶意代码<img src="empty.png" onerror ="alert('xss')"> // 转义后输出到 html 中<img src="empty.png" onerror ="alert('xss')">