
ckeditor5 已彻底弃用全局 `ckeditor` 对象,其配置方式与旧版 ckeditor4 截然不同;需通过 `htmlsupport` 插件等新机制实现 html 元素、属性、样式等白名单控制。
CKEditor5 是一个完全重写的现代富文本编辑器,不兼容 CKEditor4 的 API。你遇到的 Uncaught ReferenceError: CKEDITOR is not defined 错误,根本原因在于:CKEDITOR.replace() 是 CKEditor4 的初始化方法,而你引入的是 CKEditor5 的 CDN(/ckeditor5/38.1.1/classic/ckeditor.js),其全局对象是 ClassicEditor,而非 CKEDITOR——后者在 CKEditor5 中已被完全移除。
✅ 正确配置方式(CKEditor5)
CKEditor5 采用插件化架构,若需支持自定义 HTML(如
<script src="https://cdn.ckeditor.com/ckeditor5/38.1.1/classic/ckeditor.js"></script>
<script>
ClassicEditor
.create(document.querySelector('#editor'), {
// 启用并配置 HTML 支持
htmlSupport: {
allow: [
{
name: /.*/, // 匹配所有 HTML 元素(如 style, div, span 等)
attributes: true, // 允许所有属性(如 id, rel, data-*)
classes: true, // 允许所有 class 值
styles: true // 允许所有内联 CSS(如 style="color:red; margin:10px;")
}
]
},
// ⚠️ 注意:extraAllowedContent 在 CKEditor5 中无效,已废弃
})
.then(editor => {
console.log('Editor initialized:', editor);
window.editor = editor;
})
.catch(error => {
console.error('Editor initialization failed:', error.stack);
});
</script>? 关键说明
- htmlSupport.allow 是声明式白名单:相比 CKEditor4 的正则式 extraAllowedContent,CKEditor5 要求显式声明允许的元素、属性、类名和样式规则,更安全、更可控。
-
细粒度控制示例(推荐生产环境使用):
htmlSupport: { allow: [ { name: 'style' }, // 仅允许 <style> 标签 { name: 'div', attributes: ['id', 'class'] }, { name: 'a', attributes: ['href', 'rel'], classes: [/^external-/] }, { name: 'p', styles: ['text-align', 'margin'] } ] } - 禁用风险行为:避免使用 name: /.*/ 在生产环境无限制放行——这可能引入 XSS 风险。应始终遵循“最小权限原则”,只允许业务必需的 HTML 特性。
❌ 常见误区纠正
- ❌ 不要混用 CKEditor4 和 CKEditor5 的 API(如 CKEDITOR.replace() + ckeditor5/.../ckeditor.js);
- ❌ 不要在 CKEditor5 中寻找 CKEDITOR.config 或 CKEDITOR.instances;
- ❌ extraAllowedContent、allowedContent 等 CKEditor4 配置项在 CKEditor5 中完全无效且被忽略。
? 提示:如需迁移 CKEditor4 项目,请务必查阅 CKEditor5 迁移指南,重点关注插件替换(如 AutoEmbed 替代 Embed)、数据处理逻辑变更及事件系统重构。
通过正确使用 htmlSupport 插件,你不仅能解决 CKEDITOR is not defined 错误,更能以更健壮、更安全的方式管理富文本中的 HTML 内容。










