Skip to content

Automatically track external links opened #12

Description

@mikakruschel

I think it might be useful to also track which external links users open. It looks like navigator.sendBeacon() is the recommended function to do this without blocking the opening of the new site.

My approach is currently the following:

function trackEvent(event) {
    // check if navigator.sendBeacon is available
    if (!navigator.sendBeacon) {
        return;
    }

    const appId = "";
    const { language: locale } = navigator;
    const { location = {} } = globalThis;

    const body = {
        appID: appId,
        url: location.href,
        referrer: document.referrer,
        locale,
        type: "externalLinkClick",
        destination: event,
        clientUser: ""
    };

    if (
        /^localhost$|^127(\.\d+){0,2}\.\d+$|^\[::1?]$/.test(location.hostname) ||
        'file:' === location.protocol
    ) {
        body.isTestMode = true;
    }

    // Send tracking data in the background
    navigator.sendBeacon('https://nom.telemetrydeck.com/v2/', JSON.stringify([body]));
}

// Get the current site's origin
const currentOrigin = window.location.origin;

// Select all <a> elements
const allLinks = document.querySelectorAll('a');

// Filter for external links
const externalLinks = Array.from(allLinks).filter(link => {
    return link.href.startsWith('http') && !link.href.startsWith(currentOrigin);
});

externalLinks.forEach(link => {
    const href = link.href;
    link.addEventListener('click', function(event) {
        trackEvent(href);
    });
});

However, there are a few problems with this approach:

  • It doesn't capture when a user clicks a button that redirects them.
  • It captures every single external link; it might make more sense to only capture a predefined subset of links (perhaps by adding an attribute like td-tracked).
  • Additionally, I'm not using the WebSDK endpoint, but rather the more general endpoint.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions