Making all external links open in new tabs
When I was remaking this blog with Eleventy, I wanted to add target="_blank"
and rel="noopener"
to every external link. This was becoming a pain to do manually, so I decided to write a script to do it for me. If you want to do the same, just add this in a <script>
tag to your footer (it needs to run after all your links have rendered):
(function () {
const links = document.querySelectorAll("a[href^='https://'], a[href^='http://']")
const host = window.location.hostname
const isInternalLink = link => new URL(link).hostname === host
links.forEach(link => {
if (isInternalLink(link)) return
link.setAttribute("target", "_blank")
link.setAttribute("rel", "noopener")
})
})()
First, we use document.querySelectorAll
to target any link starting with https://
or http://
. (This is nice because it excludes relative links, such as /about
.) Second, we get the hostname for the current page. For instance, the hostname for this page is mtm.dev
. If you were on a subdomain, such as kitten.mtm.dev
, this would open any link on kitten.mtm.dev
in the same tab, but mtm.dev
or meow.mtm.dev
would open in a new tab.
On the next line, we create isInternalLink
, a function that determines if the link is pointing to the current site. Then, we loop through every link on the page; if it's an external link, we add target="_blank"
and rel="noopener"
to it.
target="_blank"
makes the link open in a new tab.
rel="noopener"
is beneficial to add to external links for security purposes. Basically, JavaScript has a window.opener
property that points to the window
of the referring HTML document. When you open an external link, JavaScript will provide it partial control over the site you came from, and this prevents it from having access. To learn more, you can read About rel="noopener" by Mathias Bynens.
Depending on your preferences, you could also add noreferrer
alongside noopener
. You'd want to do this if you want to hide that traffic is coming from your site. For instance, if you linked to my site from yours, I could check my analytics and see that your site was sending traffic to mine. If you used a link with noreferrer
, it would simply be displayed as "direct traffic" in my analytics tools.
Search engines don't consider noopener
or noreferrer
to rank pages, so you don't need to worry about the SEO implications of these. At the end of the day, this is simply a UX improvement — in my opinion, the best kind. In addition to these, there are a number of other attributes you could use — and if you'll notice, that link opens in a new tab.