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

如何让CKEditor 5的getData()方法返回自定义属性?

Fixing Missing Custom Attributes in CKEditor getData() Output

It sounds like you’ve nailed the model-view sync with your upcast/downcast converters, but the final HTML serialization step is stripping out your custom attributes. Here’s why that happens and how to fix it:

Why This Occurs

CKEditor’s data processor (the component that turns the editor’s view into HTML for getData()) uses a strict whitelist of allowed elements and attributes. Even if your view elements have custom attributes, they won’t show up in the output unless you explicitly tell the processor to preserve them.

Step-by-Step Solution

1. Whitelist Custom Attributes in the Editor Config

Use the htmlSupport configuration option to explicitly allow your custom attributes for <img> elements. Let’s say your attributes are data-custom-id and data-image-type — here’s how to add them:

ClassicEditor.create(document.querySelector('#editor'), {
  htmlSupport: {
    allow: [
      {
        name: 'img',
        attributes: ['data-custom-id', 'data-image-type']
      }
    ]
  }
})
.then(editor => {
  console.log('Editor ready:', editor);
})
.catch(error => {
  console.error('Editor init error:', error);
});

2. Double-Check Your Downcast Converter (If Needed)

Confirm your downcast converter is correctly mapping the model attribute to the view. For example:

editor.conversion.for('downcast').attributeToAttribute({
  model: 'customId',
  view: 'data-custom-id'
});

You already confirmed the view has the attribute via the inspector, but this ensures the model-view link is solid.

3. Test the Output

After updating the config, call editor.getData() again. Your <img> tags should now include the custom attributes you defined.

Bonus: Match Dynamic Attributes

If you need to allow a pattern of attributes (like all data-image-* attributes), use a regex in the htmlSupport rule:

htmlSupport: {
  allow: [
    {
      name: 'img',
      attributes: {
        key: /^data-image-.+/ // Matches any data-image-* attribute
      }
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:07:38