Sul*_* H. 6 html javascript 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;
Run Code Online (Sandbox Code Playgroud)
第二:
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);
Run Code Online (Sandbox Code Playgroud)
现在,如果这两种方式都容易受到代码注入的影响,还有没有其他方法可以像将字符串一样实现 HTML 页面中的 HTML 标签?
如果您可以完全控制正在使用的字符串的所有方面,那么两者都是安全的。
话虽如此,一般来说,.innerHTML是将 HTML 的小片段插入并解析到文档中,而不是大字符串(如您在这里),因为它成为支持的噩梦。
当您有大量内容时,例如您在此处显示的内容,HTML<template>和 JavaScript document.importNode()可能更可取,因为您有一种更简单的方法将内容注入为一系列 DOM 节点,这些 DOM 节点可以通过API 不是一堆字符串连接。这允许您动态创建元素,然后您可以使用.textContent, 而不是来填充它们.innerHTML,这消除了安全问题,因为文本不会被解析为 HTML。
| 归档时间: |
|
| 查看次数: |
3770 次 |
| 最近记录: |