Skip to content

Add Google Analytics Events to Affiliate Links

Trying to get more organized with another site of mine I wanted to start tracking information about affiliate clicks. And since I’m already using Google Analytics on that site it seemed like a relatively quick and easy solution to track clicks using events in Analytics.

So I added this bit of script to the bottom of the page. The site uses almost no JavaScript so it wasn’t worth splitting it off into a separate file.

var affLinks = document.querySelectorAll('a[rel*="sponsored"]');
for (var i = 0; i < affLinks.length; ++i) {
    affLinks[i].addEventListener('click', function () {
        var url = new URL(this.href);
        try {
            gtag('event', 'aff_click', {
                'event_category': url.hostname,
                'event_label': url.pathname
        } catch (e) {

Each link was already tagged with rel="sponsored" so it was just a matter of running a query selector to get all of the affiliate links.

For each it adds an event action aff_click. Could have been anything, but that’s what I called it. The event_category is the hostname of the outbound site. And event_label is the path to the linked page on the affiliate site.

Published inCoding

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *