缘由
最近在弄仿w3school的在线代码提交功能:http://www.w3school.com.cn/tiy/t.asp?f=jquery_hide
发现自己在做的时候,当提交的代码包含script时浏览器总数提示如下错误:
The XSS Auditor refused to execute a script in ‘http://localhost:8080/base/blog/preview‘ because its source code was found within the request. The auditor was enabled as the server sent neither an ‘X-XSS-Protection’ nor ‘Content-Security-Policy’ header.
后果就是写在DOM中的onclick
事件或者href="javascript:xxx"
都会被过滤掉。
但是相同代码放到w3school上面就没问题,看了下它的response head,并没有发现一些特殊头部,后来看源码的时候发现它在提交前做了一下正则替换:
function submitTryit()
{
var t=document.getElementById("TestCode").value;
// 关键是这2行
t=t.replace(/=/gi,"w3equalsign");
t=t.replace(/script/gi,"w3scrw3ipttag");
document.getElementById("code").value=t;
document.getElementById("tryitform").action="v.asp";
validateForm();
document.getElementById("tryitform").submit();
}
所以就明白了,提交前将script字符进行替换(不知为何等号也替换了),输出时再替换回来就可以了。
第一种做法
提交前替换,输出时再替换回来:
content = content.replace(/=/gi, 'lxaequals');
content = content.replace(/script/gi, 'lxascrlxaipttag');
输出时:
content = content.replaceAll("lxaequals", "=");
content = content.replaceAll("lxascrlxaipttag", "script");
第二种做法
或者更简单点的,在响应添加一个header即可:
response.setHeader("X-XSS-Protection", "0");