Chrome扩展开发:如何清除Facebook/Messenger网页版可编辑输入框的内容?
Chrome扩展开发:如何清除Facebook/Messenger网页版可编辑输入框的内容?
这个问题我之前也踩过坑!Messenger网页版的输入框并不是普通的contenteditable div,它是基于Lexical构建的富文本编辑器(你看元素上的data-lexical-editor="true"属性就知道了)。Lexical会自己接管内容的状态管理,所以常规的execCommand、innerHTML或者textContent修改都会被它忽略或者覆盖,这就是你的删除命令失效的原因。
给你一个适配Lexical编辑器的解决方案,同时保留对普通输入框的兼容性:
function insertTextToInput(focusedInputBox, newText) { focusedInputBox.focus(); // 先尝试针对Lexical编辑器的处理逻辑 const lexicalEditor = focusedInputBox.__lexicalEditor; if (lexicalEditor) { // 使用Lexical官方API更新内容 lexicalEditor.update(() => { const root = window.$getRoot(); // Lexical的根节点获取方法 root.clear(); // 清空所有内容 window.$insertText(newText); // 插入新文本 }); return; } // 兼容普通输入框/可编辑div的 fallback 逻辑 const range = document.createRange(); range.selectNodeContents(focusedInputBox); const sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); document.execCommand("delete"); document.execCommand("insertText", false, newText); }
为什么这个方法能生效?
Lexical编辑器会把实例挂载到对应的DOM元素的__lexicalEditor属性上,我们通过这个实例调用它的update方法,在Lexical的内部上下文里直接操作内容节点:
$getRoot()获取编辑器的根内容节点root.clear()彻底清空所有内容$insertText()插入纯文本(如果需要插入富文本可以用其他Lexical API)
调试小技巧
如果你不确定是不是Lexical的问题,可以在浏览器控制台里选中输入框元素,然后打印$0.__lexicalEditor,如果能看到编辑器实例,就说明确实是Lexical在管理内容。
备注:内容来源于stack exchange,提问作者Marco Groot
相关产品推荐
相关产品推荐

