Making all external links "open in new tab"

Hey guys
Is there some code I can add to my site that will automatically make every external link “open in new tab”?
This is for a blog, so would need to work for all pages within CMS as well as static pages :slight_smile:

2 Likes

I’d also love the ability to have the “open in new tab” functionality apply only to external links. I have a client that has a News feed comprised of articles hosted on their site and external articles as well. They’d like to have only the external articles open in a new tab. I don’t know of a way to do this. Does anyone know of any custom workarounds that can achieve this?

I drop this script in the footer code section of all my Webflow sites. Essentially it adds target="_blank" to all external links (which it finds by accessing the location.hostname of the site), then grabs all of those (plus any others that already have target="_blank") and gives them all rel="noreferrer". Seems to work consistently for me, but I can’t promise there isn’t a better way of doing it. Hope this at least gets you on the right track :slight_smile:

<script>
function ready( callback ) {
  if (document.readyState!='loading') callback();
  else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
  else document.attachEvent('onreadystatechange', function(){
    if (document.readyState=='complete') callback();
  });
}
function openAllExternalsInTabs() {
  var thisDomain = location.hostname;
  var externalDomains = 'a:not([href*="' + thisDomain + '"]):not([href^="/"])';
  var allExternalLinks = document.querySelectorAll( externalDomains );
  for( var i in allExternalLinks ) {
  	allExternalLinks[i].target = '_blank';
  }
}
function addNoReferrer() {
  var selector = '[target="_blank"]';
  var externalLinks = document.querySelectorAll( selector );
  for( var i in externalLinks) {
    externalLinks[i].rel = 'noreferrer';
  }
}
ready( function() {
	openAllExternalsInTabs(); 
	addNoReferrer();
});
</script>
5 Likes

I’m really thankful Leslie!

It worked very well, with the site I’m building, now my dynamic links inside rich texts, open in a new tab !

That’s great! I’m glad this is working for you :partying_face: