A good practice for enhancing the reading experience on any blog is to consider how external links are handled. By default, Ghost opens all links in the same tab, potentially diverting readers away from your website. In this article, we'll explore a simple JavaScript solution that allows you to open external links in a new tab without modifying any template files directly.

The Default Behavior

By default, Ghost opens all links in the same tab, including external links. This behavior can be suboptimal as it can easily disrupt the user experience and make it harder for readers to return to the content they were just reading.

The Solution

Instead of modifying the template files directly, we can use the Code Injection feature in Ghost to achieve the desired behavior. Follow these steps:

  1. Log in to your Ghost admin panel.
  2. Navigate to the Code Injection section under the Settings menu.
  3. In the Site Header section, insert the following JavaScript code snippet:
<script>
  document.addEventListener("DOMContentLoaded", function() {
    const links = document.querySelectorAll("a");
    links.forEach(function(link) {
      if (link.host !== window.location.host) {
        link.setAttribute("target", "_blank");
      }
    });
  });
</script>

Now, all external links will automatically open in a new tab, you can test the behavior by clicking on an external link anywhere on your site to confirm that it opens in a new tab.

Happy Linking! 🔗

Eric Alli @ericalli

Eric is the founder of LayeredCraft. He has worked as a designer and engineer for 15+ years and loves creating innovative and effective themes for all industries.