如何让CKEditor 5的getData()方法返回自定义属性?
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

