Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Plain Javascript to normalize target attribute for External Links
<script>
// I needed to trigger a non-interactive Google Analytics Event on external link click in
// Google Tag Manager v2. This is a hacky workaround for targeting external links on using
// a trigger like this:
// Event Type: Link Click [element: target] [starts with] ["_"]
// This is used as a HTML tag in Google Tag Manager v2 to normalize all external <A> links
// to have a "target" attribute. Priority 100, Triggered on All Pages and Event = gtm.dom
(function(){
// Find external links and fix target (target not set, href isn't relative, current domain isn't in href)
var fixlinks = document.querySelectorAll('a:not([target]):not([href*="'+window.location.host+'"]):not([href^="/"])');
for (var i=0; i<fixlinks.length; i++){
fixlinks[i].setAttribute('target', '_blank'); // or, more semantically rel=external
}
}());
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.