EditorJS搭配DeepL Chrome扩展时无法保存的解决方案求助
EditorJS 因DeepL Chrome扩展插入元素导致无法保存的解决方案
仅启用header和paragraph插件的EditorJS无法完成保存,排查发现是DeepL Chrome扩展在编辑器的纯文本节点下方插入了deeplL元素,导致EditorJS保存时校验段落数据失败,报错内容如下:
block «paragraph» skipped because saved data is invalid
关闭DeepL扩展后可恢复正常,但以下是无需用户手动关闭扩展的解决办法:
方案1:通过EditorJS的Sanitizer配置过滤无效元素
利用EditorJS内置的内容清理机制,在初始化时为paragraph和header工具添加自定义规则,过滤掉DeepL插入的元素:
const editor = new EditorJS({ holder: 'editorjs', tools: { paragraph: { sanitize: { // 保留段落默认允许的标签,禁用其他未明确授权的标签 p: true, '*': false, // 自定义清理逻辑:移除所有deeplL相关元素 custom: (node) => { if (node.classList?.contains('deeplL') || node.id === 'deeplL') { node.remove(); return null; } return node; } } }, header: { sanitize: { h1: true, h2: true, h3: true, h4: true, h5: true, h6: true, custom: (node) => { if (node.classList?.contains('deeplL') || node.id === 'deeplL') { node.remove(); return null; } return node; } } } } });
方案2:用MutationObserver监听并移除DeepL注入的元素
通过DOM变化监听,实时检测并删除EditorJS容器内的deeplL元素:
const editorContainer = document.getElementById('editorjs'); const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { mutation.addedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 直接移除当前节点中的deeplL元素 if (node.matches('.deeplL, #deeplL')) { node.remove(); } // 递归清理子节点中的deeplL元素 node.querySelectorAll('.deeplL, #deeplL').forEach(el => el.remove()); } }); }); }); // 启动监听,覆盖编辑器所有子节点 observer.observe(editorContainer, { childList: true, subtree: true }); // 编辑器销毁时记得停止监听 // editor.destroy().then(() => observer.disconnect());
方案3:通过CSS类阻止DeepL识别编辑区域
给EditorJS的根容器添加notranslate类(多数翻译扩展支持该类标记无需翻译的区域),同时配合CSS属性阻止扩展注入:
/* 给EditorJS容器添加notranslate类 */ .editorjs { translate: no; user-select: text; /* 保持可编辑,仅阻止翻译扩展识别 */ }
初始化EditorJS时,确保holder对应的容器带有notranslate类:
<div id="editorjs" class="notranslate"></div>
内容的提问来源于stack exchange,提问作者ichi pika
相关产品推荐
相关产品推荐

