Open External Links in New Window

When users click on these external links, it can be frustrating to navigate away from the current website. One solution to this problem is to open external links in new windows or tabs.

Open External Links in New Window
Photo by Fili Santillán / Unsplash

In the digital age, the web is a vast interconnected landscape. Websites often link to external sources to provide additional information or resources. However, when users click on these external links, it can be frustrating to navigate away from the current website. One solution to this problem is to open external links in new windows or tabs. In this blog post, we'll explore a code snippet that accomplishes just that.

The Code Snippet

Here's the JavaScript code snippet that we'll be discussing in this post:

// Open External Links in New Window
document.querySelectorAll('a').forEach(function(link) {
  const linkHostname = new URL(link.href).hostname;
  const currentHostname = window.location.hostname;
  // RegExp to match '', '' and any subdomain of ''
  const regex = /^(?:.*\.)?domainname\.com$/;

  if (
    !regex.test(linkHostname) &&
    linkHostname !== currentHostname &&
    !link.href.startsWith('/') &&
  ) {
    link.setAttribute('target', '_blank');
    link.setAttribute('rel', 'noopener noreferrer'); // Good practice for security reasons

Let's break down this code step by step to understand how it works and why it's a valuable addition to web development.

Understanding the Code

  1. Selecting All Links: The code begins by selecting all anchor (<a>) elements on the web page using the document.querySelectorAll('a') method. This will gather all the links present on the page, including internal and external ones.
  2. Extracting Hostnames: For each link, it extracts the hostname of the link and the current website's hostname. The new URL(link.href).hostname extracts the hostname from the href attribute of the link, and window.location.hostname retrieves the hostname of the current page.
  3. Regular Expression Matching: The code uses a regular expression (regex) to determine if the link is external. The regular expression ^(?:.*\.)?domainname\.com$ matches links that have a different hostname than the current site but belong to the same domain ( or its subdomains (,, etc.). This regex ensures that internal links are not affected.
  4. Conditions for Opening in a New Window: If the link's hostname does not match the regular expression, and it is not a link to the current hostname (to avoid opening the current page in a new tab), and it doesn't start with a / or # (to handle relative and anchor links), then it meets the conditions for opening in a new window.
  5. Setting Attributes: For links that meet these conditions, the code sets two attributes:
    • target="_blank": This attribute instructs the browser to open the link in a new tab or window.
    • rel="noopener noreferrer": This attribute is set for security reasons to prevent potentially malicious websites from accessing the window.opener property of the new window/tab, which could pose a security risk.

Now that we understand how the code works, let's discuss the benefits of automatically opening external links in new windows or tabs.

  1. Enhanced User Experience: Users can explore external content without leaving the current website. This is especially useful for references, citations, and additional reading.
  2. Improved Navigation: Users can easily return to the original website by closing the new tab or window, which simplifies navigation and encourages them to explore more content.
  3. Preventing Disruption: Opening external links in new windows prevents the abrupt interruption of the user's browsing experience. It maintains the context of the original page.
  4. Security: Setting the rel="noopener noreferrer" attribute is a security best practice. It helps protect against potential security vulnerabilities that could arise from opening untrusted external content.
  5. Accessibility: Some users with disabilities may rely on opening links in new windows or tabs for a better browsing experience. This code snippet can enhance accessibility.

Things to Consider

While the code snippet is a valuable addition to web development, there are some considerations to keep in mind:

  1. Customization: Be sure to replace in the regular expression with the actual domain name of your website. This ensures that only external links are affected.
  2. Browser Support: Be aware that browser behavior can vary. While most modern browsers support opening links in new tabs/windows, older browsers may not handle this behavior as gracefully.

In this blog post, we explored a JavaScript code snippet that automatically opens external links in new windows or tabs, enhancing the user experience and improving website navigation. We discussed how the code works and the benefits it offers in terms of usability, security, and accessibility.

By implementing this code on your website and customizing it to match your domain, you can provide a smoother and more user-friendly browsing experience, ultimately keeping your users engaged and satisfied.