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

CKEditor 5链接配置:添加target属性字段或设置默认_target=_blank

嘿,刚好对CKEditor 5的链接配置摸得比较透,这就给你一步步解决这两个问题:

1. 给链接对话框添加target属性字段

默认情况下CKEditor 5的链接对话框可能没显示target选项,你只需要在编辑器的配置里加上link.target相关配置,就能让这个字段自动出现:

ClassicEditor
    .create(document.querySelector('#editor'), {
        link: {
            target: {
                options: [
                    { label: '当前标签页打开', value: '' },
                    { label: '新标签页打开', value: '_blank' },
                    { label: '新窗口打开', value: '_window' }
                ]
            }
        }
    })
    .catch(error => {
        console.error(error);
    });

配置完之后,打开链接对话框就能看到一个目标选项的下拉菜单,用户可以自由选择链接的打开方式。

2. 设置默认target为_blank(或自定义默认值)

有两种简单的方式实现:

方式一:通过配置直接指定默认值

在刚才的link.target配置里加上default属性就行,这样用户插入新链接时,默认就会选中你设置的目标选项:

ClassicEditor
    .create(document.querySelector('#editor'), {
        link: {
            target: {
                options: [
                    { label: '当前标签页打开', value: '' },
                    { label: '新标签页打开', value: '_blank' },
                    { label: '新窗口打开', value: '_window' }
                ],
                default: '_blank' // 这里设置默认打开方式为新标签页
            }
        }
    })
    .catch(error => {
        console.error(error);
    });

如果是编辑已有的无target属性的链接,对话框也会自动选中这个默认选项,非常省心。

方式二:强制所有链接使用_blank(无需用户选择)

如果你不想让用户选择,只想强制所有链接都在新标签页打开,可以通过监听编辑器的内容变更事件来自动设置target:

ClassicEditor
    .create(document.querySelector('#editor'), {
        // 你的其他编辑器配置
    })
    .then(editor => {
        // 监听内容变化,自动给无target的链接加上_blank
        editor.model.document.on('change:data', () => {
            const links = editor.model.document.getRoot().getChildren()
                .filter(node => node.is('element', 'link'));
            
            links.forEach(link => {
                if (!link.getAttribute('target')) {
                    link.setAttribute('target', '_blank');
                }
            });
        });
    })
    .catch(error => {
        console.error(error);
    });

这种方式适合完全不需要用户干预的场景,不过更推荐第一种配置方式,灵活性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:18:54