25% off ProSNIPC25OFF

Open External Links in New Tab

Automatically adds target=_blank and rel=noopener noreferrer to all links pointing to external domains.

JavaScriptby SnipCraft
js
(function () {
  'use strict';

  document.addEventListener('DOMContentLoaded', function () {
    var siteHost = window.location.hostname;

    document.querySelectorAll('a[href]').forEach(function (link) {
      var href = link.getAttribute('href');
      if (!href) return;
      // skip fragments, relative paths, and javascript: links
      if (href.charAt(0) === '#' || href.charAt(0) === '/' || href.indexOf('javascript:') === 0) return;
      try {
        var url = new URL(href, window.location.href);
        if (url.hostname && url.hostname !== siteHost) {
          link.setAttribute('target', '_blank');
          link.setAttribute('rel', 'noopener noreferrer');
        }
      } catch (err) { /* malformed href — skip */ }
    });
  });
})();
#external#javascript#links#security#ux