Created
October 29, 2023 17:08
-
-
Save henshaw/fd0a7d5a819b723126f6709bbe621b45 to your computer and use it in GitHub Desktop.
Pattern matching event tracking with Fathom Analytics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
document.querySelectorAll('[rel="sponsored"]').forEach(item => { | |
item.addEventListener('click', event => { | |
let linkUrl = new URL(item.getAttribute('href'), window.location.href); | |
// Using the second argument to handle relative URLs | |
let currentHostname = window.location.hostname; | |
if (linkUrl.hostname !== currentHostname) { | |
// If the link's hostname is different from the current page's hostname | |
let domainParts = linkUrl.hostname.split('.'); | |
let domainName = domainParts.length > 1 ? domainParts[domainParts.length - 2] : domainParts[0]; | |
fathom.trackEvent(`Affiliate: ${domainName}`); | |
} | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Referenced in the article, "Fathom Analytics adds dynamic event and goal tracking."