【发布时间】:2023-03-13 17:36:01
【问题描述】:
有人告诉我在我的 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 页面中?
【问题讨论】:
-
不推荐这两种方式。在元素中使用 childNodes 时,您可能会遇到一些问题
-
欲了解更多信息,请参阅DOM based XSS Prevention Cheat Sheet。
标签: javascript html security xss innerhtml