Automatically Open External Links in a New Tab in Shopify
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!
Comments