few slightly rotated lines in the background, a link icon in the foreground
web development

2 min read

Simple Markdown Plugin to Open External Links in New Tab

Published on:

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';
      }
    });
  }
}

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],
  },
});

Read more

a man's downer body in a suit sitting down on a high chair

I Prepare Extremely and Early by Learning Finance and Economics

few connected dots, a mountain's top in the background

Align Your Goals