链接扩展
链接扩展为编辑器添加了对 <a> 标签的支持。该扩展也是无头的,没有实际的用户界面来添加、修改或删除链接。下面的使用示例使用原生 JavaScript 提示框来向您展示这可以如何工作。
在实际应用中,您可能会添加一个更复杂的用户界面。
粘贴的 URL 将会自动转换为链接。
安装
npm install @tiptap/extension-link设置
protocols
您希望被识别为链接的其他自定义协议。
默认值: []
Link.configure({
protocols: ['ftp', 'mailto'],
})默认情况下,linkify 会在协议的末尾添加 //,但是通过传递 optionalSlashes 选项可以更改该行为。
Link.configure({
protocols: [
{
scheme: 'tel',
optionalSlashes: true,
},
],
})autolink
如果启用,将在您输入时自动添加链接。
默认值: true
Link.configure({
autolink: false,
})openOnClick
如果启用,链接将在点击时打开。
默认值: true
Link.configure({
openOnClick: false,
})enableClickSelection
If enabled, clicking on a link will select the link.
Default: false
Link.configure({
enableClickSelection: true,
})linkOnPaste
如果粘贴的内容仅包含 URL,则将链接添加到当前选择中。
默认值: true
Link.configure({
linkOnPaste: false,
})defaultProtocol
当未定义协议时,linkOnPaste 和 autolink 使用的默认协议。
默认情况下,为 example.com 生成的 href 是 http://example.com,并且该选项允许自定义该协议。
默认值: http
Link.configure({
defaultProtocol: 'https',
})HTMLAttributes
应添加到渲染的 HTML 标签中的自定义 HTML 属性。
Link.configure({
HTMLAttributes: {
class: 'my-custom-class',
},
})移除和覆盖现有 HTML 属性
您可以向 HTMLAttributes 添加 rel: null 以移除默认的 rel="noopener noreferrer nofollow"。您还可以使用 rel: "your-value" 来覆盖默认值。
这也可以用于更改 target 的默认值为 _blank。
Link.configure({
HTMLAttributes: {
// 更改 rel 为不同的值
// 允许搜索引擎跟踪链接(移除 nofollow)
rel: 'noopener noreferrer',
// 完全移除 target 以便链接在当前标签页打开
target: null,
},
})isAllowedUri
一个允许自定义链接验证的函数,修改默认的验证逻辑。此函数接受 URL 和一个包含附加属性的上下文对象。
参数:
url: 要验证的 URL。ctx: 包含以下内容的对象:defaultValidate: 执行默认 URL 验证的函数。protocols: URL 允许的协议数组,例如["http", "https"]。defaultProtocol: 默认协议(例如,'http')。
返回值: boolean - 如果 URL 有效则返回 true,否则返回 false。
此函数使您能够在自动链接 URL 时强制执行允许的协议或域的规则。
// 验证 URL 仅接受非相对 URL
Link.configure({
isAllowedUri: (url, ctx) => ctx.defaultValidate(url) && !url.startsWith('./'),
})validate (已废弃)
此函数已被更具描述性的 shouldAutoLink 函数取代。如果提供,validate 函数将替代 shouldAutoLink 函数。
shouldAutoLink
定义有效链接是否应该在编辑器内容中自动链接。
参数:
url: 已通过验证的 URL。
返回值: boolean - 如果链接应该自动链接,则返回 true,如果不应该,则返回 false。
使用此函数根据 URL 控制自动链接行为。
// 示例: 仅当 URL 是安全的时自动链接
Link.configure({
shouldAutoLink: (url) => url.startsWith('https://'),
})命令
setLink()
链接所选文本。
editor.commands.setLink({ href: 'https://example.com' })
editor.commands.setLink({ href: 'https://example.com', target: '_blank' })toggleLink()
从所选文本添加或移除链接。
editor.commands.toggleLink({ href: 'https://example.com' })
editor.commands.toggleLink({ href: 'https://example.com', target: '_blank' })unsetLink()
移除链接。
editor.commands.unsetLink()键盘快捷键
没有键盘快捷键
此扩展没有绑定特定的键盘快捷键。不过您可能会在 Mod-k 上打开您的自定义用户界面。
获取当前值
您知道可以使用 getAttributes 来查找当前设置的属性,例如当前的 href 吗?这与 命令 (它改变状态)不同,它只是一个方法。它可能看起来是这样的:
this.editor.getAttributes('link').href