setAttribute()和XSS

Ben*_*son 4 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);
Run Code Online (Sandbox Code Playgroud)

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

Poi*_*nty 8

没有必要使用"setAttribute":

script.src = 'http://fake.com?src=' + encodeURIComponent(document.location.href);
Run Code Online (Sandbox Code Playgroud)

我不知道XSS漏洞会在哪里潜入.我猜想,"fake.com"中的服务器代码必须对"src"参数的奇怪值进行"强化",但无论你的Javascript是什么样子,这都是真的.