说明如何为 CKEditor 5 新增自定义过滤插件

解读

国内甲方对“内容安全”与“格式洁癖”要求极高:政府门户要过滤敏感词,金融站点要脱敏卡号,集团门户要统一外链白名单。CKEditor 5 默认的 htmlSupport 与 htmlEmbed 只能做通用标签/属性过滤,颗粒度不足,因此面试常问“你能否写个插件,把不符合业务规则的字符在输入阶段就干掉,而不是等 Drupal 保存后再清”。这道题考察三点:

  1. 是否理解 CKE5 的“插件即 ES6 模块”与“命令—转换—模式”架构;
  2. 是否能把插件正确注册到 Drupal 的 editor.editor.yml,并随配置导出同步到生产;
  3. 是否兼顾性能与可维护性,比如用 model.deleteContent 而不是正则暴力替换,且提供单元测试。

知识点

  1. CKEditor 5 插件骨架:继承 Plugin 类,实现 init(),在 editor.conversion.for('upcast') 监听 element 或 text 事件。
  2. Drupal 侧集成:通过 hook_editor_xss_filter_alter() 可补充服务端二次校验,但面试重点在前端插件。
  3. 配置化:利用 Drupal 的 CKEditor5PluginDeriver 把白名单/正则写成配置实体,实现“插件一次部署,规则后台可调”。
  4. 缓存友好:插件内部对同一规则生成 memoized 函数,避免每次按键都 new RegExp。
  5. 测试:CKE5 官方用 @ckeditor/ckeditor5-dev-tests,Drupal 侧用 FunctionalJavascriptTestBase 驱动 ChromeHeadless,断言“粘贴非法字符串后 model.document.getRoot().getChild(0).data 不含非法字符”。

答案

步骤概览:

  1. 建立模块 custom_ckeditor_filter,目录 modules/custom/custom_ckeditor_filter。
  2. 在 modules/custom/custom_ckeditor_filter/assets/ckeditor5_plugins/CustomFilter/src 创建插件主文件:
// customfilterediting.js
import Plugin from '@ckeditor/ckeditor5-core/src/plugin';

export default class CustomFilterEditing extends Plugin {
  init() {
    const editor = this.editor;
    const schema = editor.model.schema;
    const conversion = editor.conversion;
    const settings = editor.config.get('customFilter') || { rules: [] };

    // 注册 post-fixer,在 model 应用前统一过滤
    editor.model.document.registerPostFixer(writer => {
      let changed = false;
      for (const entry of editor.model.document.differ.getChanges()) {
        if (entry.type === 'insert' && entry.name === '$text') {
          const textNode = entry.position.textNode;
          if (!textNode) continue;
          let text = textNode.data;
          settings.rules.forEach(rule => {
            text = text.replace(rule.regex, rule.replace);
          });
          if (text !== textNode.data) {
            writer.setText(text, textNode);
            changed = true;
          }
        }
      }
      return changed;
    });
  }
}
  1. 在同一目录补充 customfilter.js 作为 UI 插件(若仅需后台过滤可省略 UI)。
  2. 创建 modules/custom/custom_ckeditor_filter/ckeditor5_plugins/custom_filter/plugin.yml:
ckeditor5_plugins:
  custom_filter:
    path: 'assets/ckeditor5_plugins/CustomFilter'
    filename: 'customfilter.js'
    plugins: [CustomFilterEditing]
    config: |
      customFilter:
        rules:
          - { regex: '/\\b(?:敏感词1|敏感词2)\\b/g', replace: '' }
          - { regex: '/\\d{16}/g', replace: '****' }
  1. 在模块 custom_ckeditor_filter.module 声明插件:
function custom_ckeditor_filter_ckeditor5_plugin_info_alter(array &$plugins) {
  $plugins['custom_filter'] = [
    'id' => 'custom_filter',
    'class' => '\Drupal\custom_ckeditor_filter\Plugin\CKEditor5Plugin\CustomFilter',
    'provider' => 'custom_ckeditor_filter',
    'config' => ['rules' => []],
  ];
}
  1. 新建 src/Plugin/CKEditor5Plugin/CustomFilter.php,实现 CKEditor5PluginDefault 接口,把 plugin.yml 的 config 注入到 JS。
  2. 在 config/install/editor.editor.full_html.yml 的 settings: plugins: 段增加:
custom_filter:
  rules:
    - { regex: '/\\b(?:敏感词1|敏感词2)\\b/g', replace: '' }
  1. 导出配置 drush cex,随 CI 部署;在 PHPUnit 中写 CustomFilterTest.php,用 $this->assertStringNotContainsString('敏感词1', $raw_html) 验证。

至此,自定义过滤插件完成,输入阶段即拦截,符合国内安全审计“先审后发”要求。

拓展思考

  1. 如果规则需要热更新而不走配置导出,可把规则存为 Drupal 自定义内容实体,通过 drupalSettings 注入,前端插件在 init() 里异步 fetch('/api/filter-rules');注意此时需给接口加缓存标签,规则更新后 cache-tags 自动刷新。
  2. 当站点开启 BigPipe 且使用 CKE5 内嵌于 Layout Builder 时,需把插件脚本声明为 library-dependency,防止异步块渲染导致 editor.create 重复初始化。
  3. 对于“白名单外链域名”场景,可改用 upcastDispatcher 监听 <a> 元素,若 href 不在白名单则 writer.remove(element),比纯文本正则更精确,且能保留链接内文本。
  4. 若未来升级到 CKEditor 5 的“实时协作”模式,Post-Fixer 会触发多次冲突解决,需要给 writer.setText 加 options.isUndo 判断,避免协作栈被污染。