← 中文资源

简体中文版本

DOMParser 把 HTML 字符串解析成文档

DOMParser 把不可信的 HTML 字符串解析成脱离页面的独立文档:脚本不执行、图片不加载,只查询节点、提取安全文本再插入正文。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:untrusted、doc、img、safe。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。

常见问题

「DOMParser 把 HTML 字符串解析成文档」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

'<img src=/x onerror=steal()><p>Review: <b onclick=navigate()>read</b> more</p>';
const doc = new DOMParser().parseFromString(untrusted, 'text/html');
safe.textContent = doc.querySelector('p').textContent;

代码示例

// DOMParser turns an HTML string into a detached Document. Scripts
// in the markup never execute and images never load, unlike
// innerHTML on a live element — parsing is observation only.
const untrusted =
  '<img src=/x onerror=steal()><p>Review: <b onclick=navigate()>read</b> more</p>';

const doc = new DOMParser().parseFromString(untrusted, 'text/html');

// The parsed nodes exist and can be queried like any document
console.log(doc.querySelector('p').textContent);

// Event handler attributes are parsed as data, never dispatched
const img = doc.querySelector('img');
console.log(img.hasAttribute('onerror'));

// Move only trusted text into the live DOM
const safe = document.createElement('p');
safe.textContent = doc.querySelector('p').textContent;
document.body.append(safe);