繁体   English   中英

使用innerHTML,有哪些安全问题?

[英]Using innerHTML, and what are security concerns?

我被告知在我的JS代码中使用innerHTML很危险。 我确实明白了为什么,但有人可以告诉我这两种使用方式之间是否存在差异?

第一:

const onePersonArticle = create('article');
onePersonArticle.className = 'one-person';
const content = ` <label class='info-labels' for="name">NAME: </label><label id='name' class='data-labels'>${member.name}</label>
    <label class='info-labels' for="phone">PHONE: </label><label id='phone' class='data-labels'>${member.phone}</label>
    <label class='info-labels' for="code-wars">CODEWARS: </label><label id='code-wars' class='data-labels'>${member.cwb} - ${member.cwa}</label>
    <label class='info-labels' for="free-code-camp">FREECODECAMP: </label><label id='free-code-camp' class='data-labels'>${member.fccb} - ${member.fcca}</label>
    <label class='info-labels' for="notes">NOTES: </label><label id='notes' class='data-labels'>${member.notes}</label>
    <span class="person-buttons"><button type="button" name="button" class="button delete-button">⌘</button>
    <button type="button" name="button" class="button edit-button">✎</button></span>`;
onePersonArticle.innerHTML = content;

第二:

const onePersonArticle = create('article');
onePersonArticle.className = 'one-person';
onePersonArticle.innerHTML =
  ` <label class='info-labels' for="name">NAME: </label><label id='name' class='data-labels'>${member.name}</label>
    <label class='info-labels' for="phone">PHONE: </label><label id='phone' class='data-labels'>${member.phone}</label>
    <label class='info-labels' for="code-wars">CODEWARS: </label><label id='code-wars' class='data-labels'>${member.cwb} - ${member.cwa}</label>
    <label class='info-labels' for="free-code-camp">FREECODECAMP: </label><label id='free-code-camp' class='data-labels'>${member.fccb} - ${member.fcca}</label>
    <label class='info-labels' for="notes">NOTES: </label><label id='notes' class='data-labels'>${member.notes}</label>
    <span class="person-buttons"><button type="button" name="button" class="button delete-button">⌘</button>
    <button type="button" name="button" class="button edit-button">✎</button></span>`;
container.appendChild(onePersonArticle);

现在,如果两种方式都容易受到代码注入攻击,那么还有其他方法可以像HTML中的字符串一样实现HTML标记吗?

如果您完全控制所使用的字符串的所有方面,则两者都是安全的。

话虽如此,一般来说, .innerHTML是为HTML的小片段插入并解析成文档而不是大字符串(就像你在这里一样),因为它成为支持的噩梦。

当你有大量的时候,例如你在这里展示的内容, HTML <template>和JavaScript document.importNode()可能更好,因为你有一种更简单的方式将内容注入一系列DOM节点,使自己更容易通过API进行操作而不是一堆字符串连接。 这允许您动态创建元素,然后可以使用.textContent而不是.innerHTML填充它们,这样可以消除安全问题,因为文本未被解析为HTML。

暂无
暂无

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

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