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 ![]()
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 ![]()
<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>
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 ![]()
Thank you! I had another script but it didn’t work. This one works great ![]()
Hey everyone!
Saw this thread and was inspired to make a solution based on @dgleslie 's awesome code!
This script does what Leslie’s does, with the additional (optional) aspects of;
- Adding a nofollow tag
- Ability to mark links as “excluded” from the script
It also adds the target _blank and noreferrer as Leslies does!
Hope this helps anyone seeing this in future, and thanks again to Leslie for the original code!