Automatically Open External Links in a New Tab in Shopify

James Parsons by James Parsons Updated Jul 24th, 2024

If someone clicks a link in a blog post you wrote, they may be gone forever. People have short attention spans, and they may forget to return to your site. What's the solution? Open your external links in a new tab.

WordPress sites let you do this easily with plugins (like this one). Shopify does not. It has apps, sure, but over 90% of them are monthly subscriptions, and you don't want to pay for another subscription for something as simple as this.

Here's the code; just add this to your Shopify theme. If you only want it active on your blog, you can add it to main-article.liquid. Otherwise, if you want it sidewide, add it to theme.liquid or another globally-used file. Remember to wrap this in <script> </script> tags:

// Grab current domain, scan all links, and modify any that don't match it to open in a new tab

document.addEventListener("DOMContentLoaded", function() {
    const siteDomain = window.location.hostname;
    const links = document.querySelectorAll('a');
    links.forEach(link => {
        try {
          const url = new URL(link.href, window.location.origin);
          if (url.hostname !== siteDomain && url.hostname !== '') {
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
          }
        } catch (error) {
          console.error('Error processing URL:', link.href, error);
        }
    });
});

Now all external links will open in a new tab when clicked. This simple change has been proven to increase time on site metrics, reduce bounce rate, and even increase revenue. Not bad, right?

Did this help you? Questions for me? Leave me a comment below!

Related Code Snippets

Written by James Parsons

James Parsons is the founder and CEO of Content Powered, a premier content marketing agency that leverages nearly two decades of his experience in content marketing to drive business growth. Renowned for founding and scaling multi-million dollar eCommerce businesses through strategic content marketing, James has become a trusted voice in the industry, sharing his insights in Search Engine Watch, Search Engine Journal, Forbes, Entrepreneur, Inc, and other leading publications. His background encompasses key roles across various agencies, contributing to the content strategies of major brands like eBay and Expedia. James's expertise spans SEO, conversion rate optimization, and effective content strategies, making him a pivotal figure in the industry.