Strapi项目中CKEditor5关键词自动加超链接方案咨询
问题描述
我已在Strapi项目中安装了CKEditor5插件,希望实现输入关键词Google时,自动将其转换为带超链接<a href="https://www.google.com" rel="nofollow noreferrer">Google</a>的形式,无需手动添加链接。目前尝试在config目录下的ckeditor.txt文件中配置typing transformations,但自定义的Google转超链接规则无效,配置代码如下:
typing: { transformations: { include: [ 'quotes', 'typography', 'symbols', 'mathematical', // Plus, some custom transformation. { from: 'CKE', to: 'CKEditor' }, { from: 'Google', to: '<a href="https://www.google.com">Google</a>'} //this won't work ], }, }
可行实现方式
方法1:使用CKEditor5的AutoLink插件(推荐)
CKEditor5自带的AutoLink插件可识别并转换链接,通过自定义规则让它匹配特定关键词:
- 确认Strapi集成的CKEditor5已包含
AutoLink插件(通常默认自带)。 - 修改CKEditor配置文件(Strapi中一般为
config/ckeditor.js):
module.exports = { enabled: true, config: { // 保留原有工具栏等配置 link: { addTargetToExternalLinks: true, defaultProtocol: 'https://', autolink: { customRegex: [ { regex: /\bGoogle\b/g, callback: match => ({ url: 'https://www.google.com', text: match[0], attributes: { rel: 'nofollow noreferrer' } }) } ] } } } };
方法2:自定义打字转换插件
若不想依赖AutoLink,可通过自定义插件监听输入事件,直接操作编辑器模型插入链接:
// 自定义插件代码 class CustomLinkTransformer { constructor(editor) { this.editor = editor; } init() { const { model } = this.editor; this.editor.editing.view.document.on('keyup', (_, data) => { // 仅在输入空格或回车时触发检查 if (![32, 13].includes(data.keyCode)) return; const position = model.document.selection.getFirstPosition(); // 匹配"Google"长度的文本范围 const wordRange = model.createRange(position.getShiftedBy(-6), position); const text = model.getData(wordRange).trim(); if (text === 'Google') { model.change(writer => { const link = writer.createElement('link', { href: 'https://www.google.com', rel: 'nofollow noreferrer' }); writer.append(writer.createText('Google'), link); writer.insert(link, position.getShiftedBy(-6)); writer.remove(wordRange); }); } }); } } // 在Strapi的CKEditor配置中注册插件 module.exports = { enabled: true, config: { plugins: [/* 原有插件列表 */, CustomLinkTransformer], // 其他配置项 } };
原配置无效原因
typing.transformations的to参数仅支持纯文本或简单符号/格式替换,无法直接插入HTML字符串。CKEditor5基于数据模型(Model)而非直接操作HTML,传入的HTML会被当作纯文本解析,不会生成链接元素。
内容的提问来源于stack exchange,提问作者John Khor
相关产品推荐
相关产品推荐

