March 26, 2016

JavaScript: External Links in New Tabs

edit

I’ve written before about my not so mild hatred for the request to open all external links in new tabs. For those who don’t know, this is done by adding target="_blank" to the anchor tag. I don’t like doing this for so many reasons, but I’ll save that rant for another blog post.

Now, I’ve been asked to do this so often that automating this process was long overdue. I spent a few minutes and wrote some JavaScript that programmatically looks for external links and adds target="_blank" to them if necessary.

Now, the defining characteristic of an externally pointing link is that it has to be an absolute path and thus start with “http”. We can use this to target only those links. Here’s how:

function setTargetBlankOnExternalLinks() {
  const links = document.getElementsByTagName('a')

  for (var i = 0; i < links.length; i++) {
    if (/^http/.test(links[i].getAttribute('href'))) {
      const link = links[i]
      link.setAttribute('target', '_blank')
      link.setAttribute('rel', 'noopener noreferrer')
    }
  }
}

setTargetBlankOnExternalLinks() // call this after the DOM is ready

This is pretty straightforward. Find all the links, loop through them and check if they begin with “http” (The use of test() instead of match() here is important since test() returns a boolean while match() returns an array or null). This means that relative links are given a pass, and links that happen to have “http” in them elsewhere, such as “/link-to-blog-about-http” don’t get mistakenly modified.

I hope this helps and saves you some time.


Liked the post?
Give the author a dopamine boost with a few "beard strokes". Click the beard up to 50 times to show your appreciation.
Need help with your software problems?

My team and I are ready to help you. Hire Agathist to build your next great project or to improve one of your existing ones.

Get in touch
Kyle Shevlin's face, which is mostly a beard with eyes

Kyle Shevlin is the founder & lead software engineer of Agathist, a software development firm with a mission to build good software with good people.

Agathist
Good software by good people.
Visit https://agath.ist to learn more
Logo for Array.reduce()
Array.reduce()
Check out my courses!
If you enjoy my posts, you might enjoy my courses, too. Click the button to view the course or go to Courses for more information.
Sign up for my newsletter
Let's chat some more about TypeScript, React, and frontend web development. Unsubscribe at any time.