Book a Call

How to …

Make all External Links Open in a New Window

A client asked us recently to ensure all the links on their site that link to other people’s sites (external links) open in a new window. We’ve been asked to do this several times before, so we thought we’d share this how-to.

It was a biggish site and not very new. Some links are stored in MySQL, some in code. Finding all the links and changing them would have been very expensive. So we completed the task with client-side scripting.

Client-Side Scripting?

As part of any website build, we almost always include some javascript. This code runs on the user’s computer and makes changes to the page in response to the user’s actions (e.g. reveal a menu) and other factors.

Why is it a Good Idea to Open External Links in a New Window?

You worked hard to get your users to your website. If they follow a link straight off it – you’ve lost them. Sometimes, you want to keep a user on your page (e.g. they are completing a booking form), but they need to refer elsewhere; opening a new window can make a lot of sense.

It’s not uncommon. A lot of sites do it, and many users will not find it unfamiliar. Adding appropriate extra attributes can prevent your site from ‘leaking’ domain authority as you refer to other sites.

If you cannot vouch for the sites to which your sites link – either in terms of editorial content or quality – this process can ‘distance’ those sites from yours. It’s possible to insert an notice saying just that as the user clicks the link.

… Is it Ever a Bad Idea?

It certainly can be. For at least these reasons (and maybe more):

  • Once a link is open in a new window, there is no ‘back button’ getting back to your page can involve stepping out of the user’s flow. This is particularly evident on smartphones.
  • Most browsers already have an ‘Open in New Window‘ option, the kind of people who make those choices are the kind to be annoyed by you making those choices for them.
  • Users can rapidly end up with a lot of open tabs.

In short, this may not be the solution for you but for some, it really works.

How to Do It

Javascript is interactive – it looks for events on the page (e.g. mouseover, page load etc) and then does things to manipulate the HTML.

Links in HTML are defined by a <a> (anchor) tag – if the tag has an href attribute, that is where the link will go. External links are typically identified as those with an href pointing to a domain different from the current one.

For example:

<a href="https://google.com">This is a link to Google</a>Code language: HTML, XML (xml)

This will read This is a link to Google.

To make a link open in a new window, you need to add the target="_blank" attribute to the anchor tag. So:

<a href="https://google.com" target="_blank">This is a link to Google</a>Code language: HTML, XML (xml)

This will read This is a link to Google but will open in a new tab or window.

Pure Javascript

OK. We know what we know what we are looking for and we have to tools to make the changes we need. So here is some code to identify and change those links.

// Wait for the page to load before doing anything
document.addEventListener("DOMContentLoaded", () => {

  // Get the current host name
  const currentHost = window.location.hostname;

  // Select all anchor tags
  const links = document.querySelectorAll("a");

  links.forEach(link => {
    // Check if the link is external
    if (link.hostname && link.hostname !== currentHost) {
      // Set the target attribute to open in a new window
      link.setAttribute("target", "_blank");

      // Optionally, set rel="noopener noreferrer" for security
      link.setAttribute("rel", "noopener noreferrer");
    }
  });
});Code language: JavaScript (javascript)
How It Works:
  1. The DOMContentLoaded event ensures the script runs after the DOM is fully loaded.
  2. The window.location.hostname fetches the current domain name.
  3. All <a> elements are selected using document.querySelectorAll("a").
  4. Each link is checked to see if its hostname is different from the current domain.
  5. If the link is external, the target="_blank" attribute is added, ensuring it opens in a new window.
  6. The rel="noopener noreferrer" attribute is added for security reasons to prevent the new page from gaining access to the window.opener object, which can be a potential security risk.
Notes:

It’s good practice to include rel="noopener noreferrer" whenever using target="_blank". Adding these two parameters is a good security practice; it prevents potential exploitation when opening links in a new window.

This script assumes that links with the same hostname are considered internal and others external.

With jQuery

It’s a little out of fashion, jQuery, but it is still widely used. If a website already uses the framework, exploiting it makes sense – it makes for shorter code.

So here’s a quick jQuery version:

$(document).ready(function () {
  // Get the current host name
  const currentHost = window.location.hostname;

  // Select all anchor tags and iterate through them
  $("a").each(function () {
    // Check if the link is external
    if (this.hostname && this.hostname !== currentHost) {
      // Set the target attribute to open in a new window
      $(this).attr("target", "_blank")<span style="font-family: inherit; font-size: inherit; font-style: var(--theme-font-style, inherit); letter-spacing: var(--theme-letter-spacing); text-transform: var(--theme-text-transform); text-decoration: var(--theme-text-decoration);">.attr("rel", "noopener noreferrer")</span>;
    }
  });
});
Code language: PHP (php)
How It Works:
  1. The $(document).ready() ensures the script runs after the DOM is fully loaded.
  2. $("a").each() iterates over all anchor (<a>) elements on the page.
  3. For each link, this.hostname is checked to see if it’s different from the current domain.
  4. If the link is external, target="_blank" and rel="noopener noreferrer" are added to the link using jQuery’s .attr() method.

It’s quite a technical this, outside most people’s scope. But we hope it’s useful to those who might need to know how to do it. As techniques go, it’s quick, easy and effective. If you need help getting it done, contact us.

Appendix – Disavowing the Content of External Links

To alert a user that they are about to leave your site is also pretty simple. Here it is in ‘neat’ javascript:

document.addEventListener("DOMContentLoaded", () => {
  // Select all links on the page
  const links = document.querySelectorAll("a[target='_blank']");

  links.forEach(link => {
    link.addEventListener("click", event => {
      // Alert the user before navigating
      const confirmNavigation = confirm("You are about to leave this site. Continue?");
      if (!confirmNavigation) {
        // Prevent the default action if the user cancels
        event.preventDefault();
      }
    });
  });
});
Code language: JavaScript (javascript)

… and its jQuery equivalent:

$(document).ready(function () {
  // Select all links with target="_blank"
  $("a[target='_blank']").on("click", function (event) {
    // Alert the user before navigating
    const confirmNavigation = confirm("You are about to leave this site. Continue?");
    if (!confirmNavigation) {
      // Prevent the default action if the user cancels
      event.preventDefault();
    }
  });
});
Code language: JavaScript (javascript)