setAttribute()和XSS

时间:2010-12-03 22:47:26

标签: javascript security xss

我正在编写一个需要将当前页面位置写入DOM的脚本,我很担心XSS。以下Javascript代码段是否可以安全地使用XSS?

var script = document.createElement('script');
script.setAttribute('src', 'http://fake.com?src=' + encodeURIComponent(document.location.href));
document.getElementsByTagName('head')[0].appendChild(script);

我知道在各种浏览器中使用document.write()来完成同样的事情是安全,但是我没有看到任何来源讨论是否使用DOM访问方法。

1 个答案:

答案 0 :(得分:8)

无需使用“setAttribute”:

script.src = 'http://fake.com?src=' + encodeURIComponent(document.location.href);

我不知道XSS漏洞会在哪里潜入。我认为,“fake.com”中的服务器代码必须“硬化”以防止该“src”参数的奇怪值,但无论你的Javascript是什么样子,这都是真的。