tiptap 链接
这个链接扩展为编辑器添加了对 <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,
});
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 属性
您可以将 rel: null
添加到 HTMLAttributes
中,以移除默认的 rel="noopener noreferrer nofollow"
。也可以使用 rel: "your-value"
覆盖默认值。
这也可以用来更改 target
的默认值为 _blank
。
Link.configure({
HTMLAttributes: {
// 更改rel为不同的值
// 允许搜索引擎跟踪链接(移除nofollow)
rel: "noopener noreferrer",
// 完全移除target,以便链接在当前标签页打开
target: null,
},
});
validate
一个函数,用于验证每个自动链接的链接。如果存在,它将接收 href 作为参数调用。如果返回 false
,则删除链接。
可以设置规则,例如排除或包含特定域名、顶级域名等。
// 只自动链接具有协议的URL
Link.configure({
validate: (href) => /^https?:\/\//.test(href),
});
命令
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
上打开自定义 UI。
获取当前值
您知道吗,可以使用 getAttributes`方法找出当前设置了哪些属性,例如 href。请注意,这与 命令 (改变状态)不同,它只是一个方法。以下是如何实现的:
this.editor.getAttributes("link").href;
源代码
使用
查看演示:https://embed.tiptap.dev/preview/Marks/Link