如何阻止CKEditor 5移除<html>、<head>和<body>标签
CKEditor 5 保留完整HTML文档结构问题
我遇到的问题和一篇针对CKEditor 4的帖子描述一致,但我使用的是CKEditor 5版本。简单来说:
当我在CKEditor中编辑包含完整结构的HTML文档时:
<html> <head> <meta http-equiv="Content-Type" content="text/html" /> </head> <body> <p>test</p> </body> </html>
使用源代码插件查看或保存后,仅会保留以下内容:
<p>test</p>
我的编辑器配置(已注释无效尝试)
/* 导入多个插件 */ class Editor extends DecoupledDocumentEditor { constructor(document) { super(document); // this.data.processor = new XmlDataProcessor( document); // 尝试替换为Xml处理器,效果不佳 // this.editing.view.domConverter.preElements =["pre","style","head","html","body","meta"]; // this.editing.view.domConverter.unsafeElements = ["script"]; // 针对视图转换器的尝试 // this.data.processor.domConverter.preElements =["pre","style","head","html","body","meta"]; // this.data.processor.domConverter.unsafeElements = ["script"]; // 针对数据转换器的尝试 } } // 构建时包含的插件 Editor.builtinPlugins = [ /* 为清晰起见仅保留相关插件 */ Essentials, GeneralHtmlSupport, SourceEditing ];
编辑器实例化代码
DecoupledDocumentEditor .create(this.options.textArea.val(), { language: Bosecr.config.LOCALE, htmlSupport: { allow: [ { // 允许所有HTML标签及其属性、类、样式 name: /.*/, attributes: true, classes: true, styles: true } ] }, updateSourceElementOnDestroy: true }) .then(editor => { console.log("view.preElements : " + editor.editing.view.domConverter.preElements); console.log("view.unsafeElements : " + editor.editing.view.domConverter.unsafeElements); console.log("data.preElements : " + editor.data.processor.domConverter.preElements); console.log("data.unsafeElements : " + editor.data.processor.domConverter.unsafeElements); // editor.editing.view.domConverter.preElements=["pre","style","head","html","body"]; // editor.editing.view.domConverter.unsafeElements=["scripts"]; this.options.toolbarArea.append( editor.ui.view.toolbar.element ); this.options.textArea.append(editor.ui.getEditableElement()); this.options.widgets.editor = editor; }) .catch(error => { alert("编辑器创建出错 : " + error); });
已尝试的解决方法
- 添加通用HTML支持插件并配置为允许所有内容,该插件能保留带自定义样式类的div,但无法保留body标签之外的内容。
- 尝试将HtmlDataProcessor替换为XmlDataProcessor,但引发更多问题,比如非自闭合的
<br>和 无法正常处理。
疑问与求助
我不确定这些标签何时、为何被移除,猜测两种可能性:要么编辑器默认只保留body内的内容,其余全部丢弃;要么存在可配置的标签列表,被设置为移除特定标签?
我尝试修改CKEditor引擎中editing.view和data.processor两处的DomConverter,将html、body、meta、head标签添加到preElements列表,但无明显效果。我分别在编辑器创建后(then函数内)和创建前(重写构造函数时)进行了尝试。
CKEditor 4中只需设置fullPage: true就能实现完整页面编辑,我的需求应该不算特殊,肯定还有没注意到的点,求指点进一步的排查方向。
内容的提问来源于stack exchange,提问作者Marc Lefèvre
相关产品推荐
相关产品推荐

