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

时间:2017-12-22 18:11:18

标签: javascript html security xss innerhtml

我被告知在我的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标记吗?

1 个答案:

答案 0 :(得分:2)

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

话虽如此,一般来说,.innerHTML是用于插入HTML并将其解析为文档的小片段,而不是大字符串(如此处所示),因为它成为支持的噩梦。

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

相关问题