AgentReadyAI visibility appCaffeine & CommerceShopify agency
Caffeine and Commerce
Caffeine and Commerce
By Dylan HuntAugust 9th, 2022shopifyjavascript

How to Make Sure All External Links on Your Site Open in a New Tab

How to Make Sure All External Links on Your Site Open in a New Tab

I know its really annoying to add target="_blank" to every external link in your website, so I wanted to share this code you can use to make every link open in a new tab. Just put this code right above the closing </body> tag.

document.addEventListener('DOMContentLoaded', function() {
  var links = document.querySelectorAll('a[href]');
  var host = window.location.hostname;

  links.forEach(function(link) {
    var href = link.getAttribute('href');
    if (href && href.indexOf('http') === 0 && href.indexOf(host) === -1) {
      link.setAttribute('target', '_blank');
      link.setAttribute('rel', 'noopener noreferrer');
    }
  });
});

This will automatically find every link on the page that points to an external domain and set it to open in a new tab. No need to manually add target="_blank" to each one.

Make your store agent-ready

Get found and recommended by AI shopping assistants.

AgentReady adds Schema.org structured data, an llms.txt directory, and an AI-readability audit to your Shopify store, so ChatGPT, Perplexity, and Google can understand and recommend your products. Free for stores under 500 products.

Comments

Every comment here comes from a verified email. Write yours, confirm from your inbox, and it's live.

Loading comments…

Leave a comment

ShareXLinkedInFacebook

Written by Dylan Hunt, Founder, Caffeine and Commerce. We build Shopify stores that rank and that AI agents can read. Have a project? Get in touch.