Log click event on html link using Amplitude SDK

892 Views Asked by At

I'm trying to log an event when a <a> link is clicked before navigating to the final destination, this is what I have so far:

<a href="/account" data-event-type="select_account">My account</a>
document.querySelectorAll('a[data-event-type]').forEach(link => 
  link.addEventListener('click', function onLoggableActionClicked(ev) {
    ev.preventDefault();

    amplitude.getInstance().logEvent(link.getAttribute('data-event-type'));
                  
    window.location.href = link.href;
  })
)

The event fires perfectly but the event doesn't get logged, maybe because the request is ended when the browser is redirected?

I tried using a callback but waiting for it makes the navigation impossible:

function onLoggableActionClicked(ev) {
  ev.preventDefault();

  amplitude.getInstance().logEvent(link.getAttribute('data-event-type'), null, function() { window.location.href = link.href });
})

How can I log events for outbound links?

1

There are 1 best solutions below

0
docta_faustus On

You can use the beacon transport method which uses window.navigator.sendBeacon() under the hood which is designed to send asynchronous requests, ensuring their continuation even if the user navigates away:

amplitude.init('AMPLITUDE_ID', {
  transport: 'beacon',
  flushIntervalMillis: 0,
  flushQueueSize: 1,
});

https://www.docs.developers.amplitude.com/data/sdks/typescript-browser/#use-sendbeacon