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

如何在CKEditor5中允许内容包含自定义HTML标签与JavaScript代码?

CKEditor 5允许自定义HTML标签与JavaScript代码的配置方案

CKEditor 5默认会执行内容清理,移除自定义HTML标签和JavaScript代码,你之前使用的allowedContent是CKEditor 4的配置项,在CKEditor 5中不生效。以下是解决该问题的具体配置方法:

核心原理说明

CKEditor 5采用的内容过滤机制(Content Filter)与CKEditor 4完全不同,默认会过滤所有编辑器未明确支持的标签、属性、样式。要允许自定义内容,需要通过htmlSupport配置或移除相关过滤插件来实现。

方案一:完全禁用内容过滤(快速生效,注意安全风险)

通过移除ContentFilter和HtmlSanitizer插件,同时配置htmlSupport允许所有HTML内容:

config={ {
  toolbar: [ 'bold', 'italic' ],
  // 移除内容过滤与HTML清理插件
  removePlugins: [ 'ContentFilter', 'HtmlSanitizer' ],
  // 允许所有标签、属性、类、样式
  htmlSupport: {
    allow: [
      {
        name: /.*/,
        attributes: true,
        classes: true,
        styles: true
      }
    ]
  }
} }

修改后的完整React组件代码:

import React from 'react';
import { CKEditor } from "@ckeditor/ckeditor5-react";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import * as PropTypes from 'prop-types';

const HTMLEditor = ({ setHtml, content }) => {
  return (
    <div>
      <CKEditor
        editor={ClassicEditor}
        data={content}
        onChange={(event, editor) => {
          setHtml(editor.getData());
        }}
        config={ {
          toolbar: [ 'bold', 'italic' ],
          removePlugins: [ 'ContentFilter', 'HtmlSanitizer' ],
          htmlSupport: {
            allow: [
              {
                name: /.*/,
                attributes: true,
                classes: true,
                styles: true
              }
            ]
          }
        } }
      />
    </div>
  );
}

export default HTMLEditor;

方案二:精确允许指定的自定义内容(更安全)

如果不想完全禁用过滤,可以精确配置允许的自定义标签和JavaScript属性(如onclick):

config={ {
  toolbar: [ 'bold', 'italic' ],
  htmlSupport: {
    allow: [
      // 允许自定义标签 <my-custom-tag>
      {
        name: 'my-custom-tag',
        attributes: true,
        classes: true,
        styles: true
      },
      // 允许所有标签的 onclick 事件属性
      {
        name: /.*/,
        attributes: {
          onclick: true
        }
      }
    ]
  }
} }

注意事项

  • 完全禁用内容过滤会引入XSS攻击风险,仅建议在可信环境中使用(如仅内部人员编辑内容),若内容需公开渲染,需自行添加前端安全校验。
  • 经典构建(@ckeditor/ckeditor5-build-classic)默认包含ContentFilter和HtmlSanitizer插件,必须通过removePlugins移除才能关闭过滤。
  • 上述配置在你使用的37.0.1版本中完全兼容。

内容的提问来源于stack exchange,提问作者moh sajid khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:52:41