Skip to content

Instantly share code, notes, and snippets.

@henshaw
Created October 29, 2023 17:08
Show Gist options
  • Save henshaw/fd0a7d5a819b723126f6709bbe621b45 to your computer and use it in GitHub Desktop.
Save henshaw/fd0a7d5a819b723126f6709bbe621b45 to your computer and use it in GitHub Desktop.
Pattern matching event tracking with Fathom Analytics
<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>
@henshaw
Copy link
Author

henshaw commented Oct 29, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment