DEV Community

Cover image for Simple markdown plugin to open external links in a new tab
Tömő Viktor
Tömő Viktor

Posted on • Originally published at tomoviktor.com

Simple markdown plugin to open external links in a new tab

I made all the external links to be _blank. I needed this because I write every post of mine in Markdown.

Introduction

On my personal blog I have few external links in my posts. I wanted to keep people on my website by applying target="_blank" on external (those what don't reference to my site) links. This is a common and good practice too. I write my content in Markdown, so I decided to write a remark plugin. It is simple to implement, just few lines of code.

The plugin

It takes in the tree of the markdown file and looks through the links.

To check if it is an external site:

  1. Checks with a regex if link is a full url (for example: https://example.com/ will be full but /example won't be)
  2. Checks if it doesn't contain my site's starting url (edit this if you use the plugin)

If an external link is found, it sets the target to _blank. Because the element might not have any special property, first it ensures that it has data and data.hProperties.

import { visit } from 'unist-util-visit';

const site = "https://tomoviktor.com";

export function externalAnchorPlugin() {
  return function (tree, file) {
    visit(tree, 'link', (node) => {
      if (/^(https?):\/\/[^\s/$.?#].[^\s]*$/i.test(node.url) && !node.url.includes(site)) {
        node.data ??= {};
        node.data.hProperties ??= {};
        node.data.hProperties.target = '_blank';
      }
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Use it with Astro

As I mentioned in one of my other post I use the Astro web framework for my blog. Astro makes it effortless to import a Markdown plugin. All I had to do is add the function to astro.config.mjs.

import { externalAnchorPlugin } from './remarkplugins/external-anchor-plugin.mjs';

export default defineConfig({
  markdown: {
    remarkPlugins: [externalAnchorPlugin],
  },
});
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
jd2r profile image
DR

Fantastic! This is just the thing I was looking for, thanks for working through a solution.

Collapse
 
tomoviktor profile image
Tömő Viktor

I am happy that you found this useful. I searched for a simple plugin like this several times, but I could not find one. Eventually I realized it is better if I just do it myself.