Solved

Event not showing up when redirecting user to an external page on button click

  • 18 April 2024
  • 3 replies
  • 37 views

We have a button on our website. Clicking on this button will send users to an external page (a page with a different domain) in the same tab. We want to register click event on this button.

My code is something like this:

const handleClick = () => {
track(EVENT_NAME)
window.location.href = EXTERNAL_URL
}

In this case, we are not seeing the event on amplitude.

I am assuming this is because we are navigating away from website before amplitude has enough time to send the event.

We tried adding `await` to the amplitude `track` event which works but it is resulting in a slight delay which is not a good user experience.

Does anyone have any solution for this? This looks like a common use case. 

icon

Best answer by Yosimy.Cortes 18 April 2024, 21:00

View original

3 replies

Userlevel 2
Badge +5
Hi Tarun,

My name is Yosimy from Amplitude Support, happy to help!

Could you let me know what SDK you are using?

You're correct in your assumption that the event might not be getting enough time to send before the navigation occurs. This is a common issue when trying to track events that lead to a redirection.

One solution to this problem is to use the `sendBeacon()` method. This method is specifically designed to handle such cases where a small amount of critical data needs to be sent to the server before the page unloads. It sends the data asynchronously, doesn't delay the unload, and doesn't impact the performance of the next navigation.

In the Amplitude Browser 2.0 SDK, you can enable this to set the transport to use beacon only when exiting the page. Amplitude recommends adding your own event listener for the pagehide event. Here is an example:

window.addEventListener('pagehide',
() => {
amplitude.setTransport('beacon')
// Sets https transport to use `sendBeacon` API
amplitude.flush()
},
);

You can read more about the sendBeacon in the Browser SDK documentation here: https://www.docs.developers.amplitude.com/data/sdks/browser-2/#use-sendbeacon

I hope this helps! Let me know if you have any other questions.

Best,
Yosimy


P.S. Checkout upcoming events and user meetups on our events page.

Thank you @Yosimy.Cortes ! That worked.

We are using the `Amplitude Browser 2.0 SDK`.

Userlevel 2
Badge +5
Hi Tarun,

You're very welcome! I'm glad to hear that this worked for your use case. Happy to have helped!

Best,
Yosimy


P.S. Checkout upcoming events and user meetups on our events page.

Reply