繁体   English   中英

安全性:innerHTML vs textContent with API

[英]Security: innerHTML vs textContent with API

目前,我正在学习 API 以及如何在动态网站中使用它们。 我编写了一些示例网站,在那里我从 API 获取数据。

我一直在使用innerHTML将内容添加到我的页面。 我的老师在课堂上使用createElement textContentappendChild将内容添加到他的页面。 当被问到时,他解释说,innerHTML 比 textContent 更不安全,例如,如果 API 不可靠或被注入了恶意代码,innerHTML 可以编辑整个 HTML,而不仅仅是带有 textContent 的内容。 ChaseMoskal 也尝试在此评论中解释innerText vs innerHtml vs label vs text vs textContent vs externalText

我得到了基本的想法,但是,通过以下代码示例进行解释,我觉得两者都存在相同的安全问题。

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/

我没有得到或错过了什么?

当您使用innerHTML任何东西都可以在其中呈现,而您无法控制它。

检查以下示例。

 var codeSnippet = "<div style='height:100px;width:100px;background-color:red' onclick='window.console.log(\\"Anything!!!\\");'><a href='#'>Click Here</a></div>"; document.getElementById('unsafe').innerHTML = codeSnippet; document.getElementById('safe').textContent = codeSnippet;
 <div id="unsafe"> </div> <br> <div id="safe"> </div>

不同之处在于恶意代码的使用方式。 使用以下代码可能会显示不同之处:

var container = document.querySelector("#container");
var json1 = "Link to an image of my house";
var json2 = "Link to an image of my boat";
var maliciousCode = "javascript:alert('test');\" xxx=\"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/6/

您将看到第一个示例显示了弹出窗口,而第二个示例没有。 想象一下,如果是一些 javascript 访问 cookie,或观看键盘输入,例如。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM