Skip to content

Instantly share code, notes, and snippets.

@NoamGaash
Created November 7, 2022 09:07
Show Gist options
  • Save NoamGaash/74c95333e665c8d2b48ef7477d120e9d to your computer and use it in GitHub Desktop.
Save NoamGaash/74c95333e665c8d2b48ef7477d120e9d to your computer and use it in GitHub Desktop.
google analytics tag outbound links
document.addEventListener('DOMContentLoaded', ()=>{
if ("ga" in window) {
tracker = ga.getAll()[0];
var a = document.getElementsByTagName("a");
for(i = 0; i < a.length; i++) {
if (a[i].href.indexOf(location.host) == -1 && a[i].href[0] != "#") {
let url = a[i].href;
a[i].onclick = function(e){
tracker.send('event', 'outbound', 'click', url.replace("https:\/\/", ""), {
'transport': 'beacon',
'hitCallback': function(){window.open(url);}
});
e.preventDefault();
return false;
}
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment