441 字
2 分钟
Fuwari:如何让外部链接自动在新标签页打开
为什么需要这个优化?
Fuwari 默认对 Markdown 中的链接处理较为简单,点击外部链接时会直接在当前页面跳转。这对于读者来说并不友好:当他们想看一眼参考资料时,原本的阅读进度就被迫中断了。
为了解决这个问题,我们可以利用 rehype-external-links 插件,它能自动识别外部链接并为其注入 target="_blank" 属性,从而让外部链接自动在新标签页打开。
Waiting for api.github.com...
安装插件
进入博客根目录,使用包管理器安装插件:
pnpm add rehype-external-links配置Astro 配置文件
安装完成后,我们需要在 astro.config.mjs 中启用它。
在博客根目录编辑 astro.config.mjs 文件,在文件顶部引入插件:
import rehypeComponents from "rehype-components";import rehypeExternalLinks from "rehype-external-links";import rehypeKatex from "rehype-katex";找到 markdown 配置部分的 rehypePlugins 数组,添加 rehypeExternalLinks 配置:
markdown: { //... 其他配置 rehypePlugins: [ rehypeKatex, [ rehypeExternalLinks, { target: "_blank", rel: ["nofollow", "noopener", "noreferrer"], }, ], rehypeSlug, //... 其他插件 ] //... 其他配置 }参数说明
-
target: "_blank":强制链接在新标签页打开。 -
rel: ['nofollow', 'noopener', 'noreferrer']:添加安全属性。nofollow:告诉搜索引擎不要追踪此链接,保护站点权重。noopener & noreferrer:阻断新页面对原页面的控制权限,防范恶意脚本攻击。
进阶技巧
该插件也可以给外部链接加一个小图标(比如 ↗ ),你可以添加一个 content 属性:
rehypeExternalLinks,{ target: "_blank", content: { type: "text", value: "↗" }},这样,所有的外部链接后面都会自动跟一个箭头符号,清晰地提示用户 这是一个外部跳转↗ 。
对比测试
Fuwari:如何让外部链接自动在新标签页打开
https://www.smaritron.top/posts/ext-links-blank/