【发布时间】:2018-07-09 02:31:40
【问题描述】:
目前,我是否正在学习 API 以及如何将它们与动态网站一起使用。我编写了一些示例网站,从 API 获取数据。
我一直在使用innerHTML 将内容添加到我的页面。
我的老师在课堂上使用createElement textContent 和appendChild 将内容添加到他的页面。
当被问到时,他解释说 innerHTML 比 textContent 更不安全,例如如果 API 不可靠或被注入恶意代码,innerHTML 可以编辑整个 HTML,而不仅仅是带有 textContent 的内容。 ChaseMoskal 也尝试在此评论中解释 innerText vs innerHtml vs label vs text vs textContent vs outerText
我明白了基本的想法,但是,通过以下代码示例进行解释,我觉得两者都存在相同的安全问题。
var container = document.querySelector("#container");
var json1 = "Link to an image of my house";
var json2 = "Link to an image of my boat";
var jsonMaliciousCode = "maliciousCode3000"
// Create p element with innerHTML
container.innerHTML += "<a href=\""+maliciousCode+"\">" + json1 + "</a>";
// Create p element with textContent, href and appendChild
var innerExample = document.createElement('a');
innerExample.textContent = json2;
innerExample.href = maliciousCode;
container.appendChild(innerExample);
工作示例:https://jsfiddle.net/vh8hLhbj/4/
什么是我没有得到或错过的?
【问题讨论】:
-
如果你要让用户设置元素的href,你可能至少要验证协议
-
这不仅不安全,而且速度很慢并且会破坏你的 DOM。
标签: javascript html json security