← 中文资源

简体中文版本

textContent 让不可信文本失去杀伤力

textContent 把不可信文本存成纯文本节点,同样的字符串经 innerHTML 写入会被当作标记解析;含 onerror 的片段从无害字符串变成真实的事件属性。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:comment、unsafe、safe、label。 顶层对象字面量把 author、body 定成普通值——没有派生,背后也没有导入。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 每一步打印都带着自己的标签:innerHTML parsed elements:、safe child nodes:、elements inside safe:。

常见问题

「textContent 让不可信文本失去杀伤力」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

核心语句

safe.append(label, ': ', comment.body); // append treats string arguments as text nodes
console.log('safe child nodes:', safe.childNodes.length);
const comment = { author: 'ada', body: '<img src=x onerror="steal()">hi' };
unsafe.innerHTML = '<b>' + comment.author + '</b>: ' + comment.body;

代码示例

// comment.body comes from an untrusted source: the same string through two rendering paths produces completely different results
const comment = { author: 'ada', body: '<img src=x onerror="steal()">hi' };

// innerHTML: the string enters the HTML parser and <img onerror> becomes a real element with a real attribute
const unsafe = document.createElement('p');
unsafe.innerHTML = '<b>' + comment.author + '</b>: ' + comment.body;
console.log('innerHTML parsed elements:', unsafe.querySelectorAll('*').length);

// createElement + textContent: the text never reaches the parser, so markup shows up literally
const safe = document.createElement('p');
const label = document.createElement('b');
label.textContent = comment.author;
safe.append(label, ': ', comment.body); // append treats string arguments as text nodes
console.log('safe child nodes:', safe.childNodes.length);
console.log('elements inside safe:', safe.querySelectorAll('*').length);
console.log('visible text:', safe.textContent);

// double-check: no element inside safe carries an onerror attribute
console.log('handlers in safe:', safe.querySelectorAll('[onerror]').length);