Automatically Open External Links in a New Tab in Shopify

Updated 07/24/2024, Posted 07/24/2024 by James Parsons James Parsons 0 Comments

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

Hi, I'm James Parsons! I founded Content Powered, a content marketing agency where I partner with businesses to help them grow through strategic content. With nearly twenty years of SEO and content marketing experience, I've had the joy of helping companies connect with their audiences in meaningful ways. I started my journey by building and growing several successful eCommerce companies solely through content marketing, and I love to share what I've learned along the way. You'll find my thoughts and insights in publications like Search Engine Watch, Search Engine Journal, Forbes, Entrepreneur, and Inc, among others. I've been fortunate to work with wonderful clients ranging from growing businesses to Fortune 500 companies like eBay and Expedia, and helping them shape their content strategies. My focus is on creating optimized content that resonates and converts. I'd love to connect – the best way to contact me is by scheduling a call or by email.