监听 contenteditable 内容变化必须用 mutationobserver 配合 input、compositionend 和 blur 事件,因其能捕获粘贴、输入法、撤销等 input 无法覆盖的操作,且需配置 childlist: true、subtree: true 和 characterdata: true,并校验 isconnected。

contenteditable 属性本身变化(比如从 "true" 改成 "false")不会触发任何原生事件,浏览器不提供监听机制。你真正要监听的不是属性值变更,而是**内容实际被修改了**——这必须靠组合 DOM 变更监听 + 用户输入行为捕获来实现。
为什么只监听 input 事件会丢内容
input 事件对键盘按键、删除、回车响应及时,但对以下操作完全静默:
- 右键粘贴富文本(含
<style></style>、<script></script>、嵌套<div>)<li>中文输入法上屏(compositionstart → compositionupdate → <code>compositionend中间段不触发input) - 拖拽插入图片或文本块
- Ctrl+Z / Ctrl+Y 撤销重做
- 通过 JS 直接调用
el.innerHTML = '...'或document.execCommand(已废弃但仍有使用) - 必须设
childList: true和subtree: true:否则粘贴一段<div><p>hello</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8272" title="anything-to-html"><img src="https://img.php.cn/upload/skill/000/000/081/179195588450431.jpg" alt="anything-to-html" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill8272" title="anything-to-html" class="overflowclass">anything-to-html</a> <p class="overflowclass">将调研报告、方案对比、数据分析、需求梳理、会议纪要、设计说明、代码评审、学习笔记等任务产物输出为可在浏览器直接打开的单文件 HTML,替代 Markdown 作为最终交付物。Markdown 在信息密度、视觉清晰度和可分享性上已跟不上 AI 产物的丰富度,HTML 能同时承载排版、表格、SVG 等。</p> </div> <a rel="nofollow" href="/xiazai/skill8272" title="anything-to-html" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div></div>时,只会看到div被插入,看不到内部p和文本节点变更 - 必须校验
mutation.target.isConnected:避免监听已移出文档的旧节点(常见于 Vue/React 组件卸载后未disconnect()) - 不要监听
document或全局容器:广告脚本、埋点代码插入的节点会制造海量无效回调 - 若需捕获 class/style/data-* 修改(如高亮切换、块类型标记),加
attributes: true并指定attributeFilter: ['class', 'data-block-type'],否则噪音爆炸
这些都不是“输入”,而是 DOM 结构变动,input 无能为力。
MutationObserver 是唯一可靠方案
监听 contenteditable 容器的内容变化,必须用 MutationObserver,且配置不能省略关键选项:
示例最小可用监听:
const editor = document.querySelector('[contenteditable]');
if (!editor || !editor.isConnected) return;
<p>const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.type === 'childList' || mutation.type === 'characterData') {
// 内容确实变了,这里同步保存或更新预览
syncContent(editor);
}
});
});</p><p>observer.observe(editor, {
childList: true,
subtree: true,
characterData: true,
// attributes: true,
// attributeFilter: ['class', 'data-block-type']
});</p>
input + compositionend + blur 必须组合兜底
MutationObserver 虽强,但无法区分“用户主动编辑”和“脚本自动注入”。真实业务中仍需配合用户意图信号:
-
input:覆盖高频小粒度变更(打字、删字、快捷键格式化) -
compositionend:中文输入法完成上屏后必触发,此时textContent才稳定 -
blur:防用户编辑后直接切 Tab 或点保存按钮,确保最后变更不丢失
注意:别在 input 回调里直接读 el.innerHTML —— 用户粘贴了 <img src="x" onerror="alert(1)"> 就会执行脚本。优先用 el.textContent,或走白名单清洗流程(如只保留 p、strong、ul/li)。
容易被忽略的三个细节
一是 contenteditable 元素初始为空时,首次点击可能不聚焦,得手动 el.focus() 并用 Range 把光标定位到末尾;二是 SSR 渲染的页面中,DOM 尚未挂载完成就调用 observe() 会失败,建议包裹在 requestAnimationFrame 里;三是移动端 Safari 对 contenteditable 的 input 触发时机不稳定,MutationObserver 反而更准,但要注意 selectionchange 事件延迟问题。










