Automatically open external links in a new tab in Eleventy
Although some frown on the practice, I prefer to have external links open in a new tab. I use Eleventy for this site and write my posts in Markdown. I want to be able to easily add the target="_blank" attribute to external links in my Markdown files.
I started with the markdown-it-attrs plugin, which allows me to easily add classes and data attributes to elements in Markdown. It is very useful, but it doesn't allow me to automatically add the target="_blank" attribute to all external links in the post.
I then found the markdown-it-link-attributes plugin, which turned out be the solution for handling external links.
markdown-it-attrs
Eleventy uses the markdown-it parser which we can extend with other plugins. I first added markdown-it-attrs, which enables easy adding of classes and other attributes in Markdown. It does not appear to support adding of id attributes.
For example, we can have this in our Markdown file:
# This is a header with a class {.style-me}
This is a paragraph with a data attribute. {data-toggle=modal}
This is [an external link](https://my-external-link.com){target="_blank" rel="noopener noreferrer"} embedded in some text.
And the HTML output is this:
<h1 class="style-me">This is a header with a class</h1>
<p data-toggle="modal">This is a paragraph with a data attribute.</p>
<p>This is <a href="https://my-external-link.com" target="_blank" rel="noopener noreferrer">an external link</a> embedded in some text.</p>
To add this feature in Eleventy, we install the npm package in our project:
npm install markdown-it-attrs --save-dev
Then add it in our eleventy.config.sys file:
// eleventy.config.sys
import markdownItAttrs from "markdown-it-attrs";
export default async function (eleventyConfig) {
...
// markdown-it-attrs
eleventyConfig.amendLibrary("md", (mdLib) => mdLib.use(markdownItAttrs));
...
};
This works well and is handy to have, but unfortunately it requires me to manually insert the {target="_blank" rel="noopener noreferrer"} code after every external link in a post. I want something that automatically inserts the attributes for every external link.
The solution: markdown-it-link-attributes
In searching for a solution, I came across markdown-it-link-attributes, which works perfectly for my purposes.
Install the plugin:
npm install markdown-it-link-attributes --save-dev
Configure it in eleventy.config.js:
// eleventy.config.sys
import mila from "markdown-it-link-attributes";
export default async function (eleventyConfig) {
...
const milaOptions = {
matcher(href) {
return href.startsWith("http");
},
attrs: {
target: "_blank",
rel: "noopener noreferrer",
},
};
eleventyConfig.amendLibrary("md", (mdLib) => mdLib.use(mila, milaOptions));
...
};
This will automatically add the target="_blank" rel="noopener noreferrer" attributes to all links that start with "http", i.e. all external links.
- ← Previous
Using LightningCSS with Eleventy 3