You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询CKEditor5过滤内容(样式、类、元素)的原因及简便解决方案

CKEditor5 保留自定义HTML标签与类的解决方案

核心原因

CKEditor5采用**内容过滤(Content Filtering)**机制,默认仅允许编辑器预设的标签、属性和类,自定义内容会被自动清理,这和CKEditor4的allowedContent逻辑完全不同。

简便解决方案(无需编写复杂插件)

方法1:使用官方GeneralHtmlSupport插件(推荐)

CKEditor5官方提供了GeneralHtmlSupport插件,专门用于配置允许自定义HTML内容,步骤如下:

  1. 安装插件(npm环境):
    npm install @ckeditor/ckeditor5-html-support
    
  2. 在编辑器配置中启用并设置规则:
    import { GeneralHtmlSupport } from '@ckeditor/ckeditor5-html-support';
    
    ClassicEditor
        .create( document.querySelector( '#editor' ), {
            plugins: [ GeneralHtmlSupport, /* 其他已启用的插件 */ ],
            htmlSupport: {
                allow: [
                    // 允许带任意类的div标签
                    {
                        name: 'div',
                        attributes: {
                            class: true // 也可指定具体类,如 'myclass'
                        }
                    },
                    // 可添加更多规则,比如允许带自定义属性的span
                    // { name: 'span', attributes: { 'data-id': true } }
                ]
            }
        } )
        .catch( error => {
            console.error( error );
        } );
    
    该方式能精准控制允许的内容,安全性更高。

方法2:完全禁用内容过滤(仅信任内容来源时使用)

如果需要无条件保留所有HTML内容,可通过配置关闭过滤,但存在XSS风险,谨慎使用:

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        htmlSupport: {
            allow: [
                {
                    name: /.*/, // 允许所有标签
                    attributes: true, // 允许所有属性
                    classes: true, // 允许所有类
                    styles: true // 允许所有样式
                }
            ]
        }
    } )
    .catch( error => {
        console.error( error );
    } );

现成第三方插件

社区已有封装好的插件可直接使用,比如ckeditor5-full-html,它实现了类似CKEditor4allowedContent=true的全HTML支持,安装后配置启用即可。

内容的提问来源于stack exchange,提问作者MattOpen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:35:20