contenteditable 粘贴网页带 14 层 span:Chrome 120 怎么清干净

后台富文本编辑器用 Contenteditable 实现,从新闻页复制一段带样式的文字粘进去,DOM 里立刻多出 14 层 span,字体颜色、行高、字间距全被带进来。粘十几次之后 innerHTML 从 1.2KB 涨到 41KB,保存后前台页面跟着变形,标题行高被撑到 40px。

试过在 paste 事件里直接 e.preventDefault() 再读 text/plain,样式是没了,但换行和图片一起丢,三段文字挤成一行,用户反馈粘贴后要手动回车。也试过粘完用正则把 style 和 class 全剥掉,14 层 span 剥完还剩 6 层空标签, 和 Word 生成的 o:p 标签漏网。

根因是 Chrome 120 粘贴时同时写入 text/html 和 text/plain,text/html 里带着完整内联样式和 mso- 前缀的类名。直接 insertHTML 等于把整棵子树搬进编辑器,样式也就跟着进来了。

改成拦截 paste 后自己走白名单。把 text/html 塞进一个脱离文档的 div,递归遍历,只保留 p、br、strong、em、a、img,其余节点用子节点替换掉自己;属性只留 href 和 src,href 必须以 http 或 https 开头,src 是 data: 或 blob: 的一律丢弃,避免把整张图塞进正文。

重建节点用 createElement 而不是 cloneNode,mso 的 style 和 lang 属性自然不会再带过来。同一份带 14 层 span 的新闻内容粘 200 次,DOM 最多 3 层,innerHTML 稳定在 2KB 以内。

验收口径写成三条:从百度新闻、Word 2019、Chrome 自带复制三个来源各粘一次,层数不超过 3、体积小于 3KB、前台标题行高与编辑器一致。三条都对上才发版。

const allow = new Set(['P','BR','STRONG','EM','A','IMG']);
editor.addEventListener('paste', (e) => {
  e.preventDefault();
  const box = document.createElement('div');
  box.innerHTML = e.clipboardData.getData('text/html');
  const out = document.createElement('div');
  const walk = (node, dest) => {
    node.childNodes.forEach((n) => {
      if (n.nodeType === 3) {
        dest.appendChild(n.cloneNode());
        return;
      }
      if (!allow.has(n.tagName)) {
        walk(n, dest);
        return;
      }
      const el = document.createElement(n.tagName);
      if (n.tagName === 'A') el.href = n.getAttribute('href');
      if (n.tagName === 'IMG') el.src = n.getAttribute('src');
      dest.appendChild(el);
      walk(n, el);
    });
  };
  walk(box, out);
  document.execCommand('insertHTML', false, out.innerHTML);
});

您可以还会对下面的文章感兴趣: