Amplitude: Option to use "beacon" transport

For many webapps, it’ll be better for Amplitude to be configured to use beacon transport and then tying it to the event handler for pageHide event. Something to consider adding support for and to consider how this works for embedded cases.

See this:

Unlike standard network requests, sendBeacon sends events in the background, even if the user closes the browser or leaves the page.

Reminder that pageHide is fired in these cases:

The pagehide event is sent to a Window when the browser hides the current page in the process of presenting a different page from the session’s history . For example, when the user clicks the browser’s Back button, the current page receives a pagehide event before the previous page is shown.

So this is really helpful to make sure events aren’t lost especially since users on surveys, esp in embedded cases, can nav away, switch tabs, etc.

They show this code:

amplitude.init(API_KEY, 'user@amplitude.com', 
  {
    transport: TransportType.SendBeacon,
    // To make sure the event will be scheduled right away.
    flushIntervalMillis: 0,
    flushQueueSize: 1,
  }
);

Additionally, they recommend adding this on pageHide event. e.g.

useEffect(() => {
    function handlePageHide() {
      if (window && 'amplitude' in window) {
        window.amplitude.setTransport('beacon');
        window.amplitude.flush();
      }
    }
    window.addEventListener('pagehide', handlePageHide);

    return () => {
      window.removeEventListener('pagehide', handlePageHide);
    };
  }, []);

There may be some customers who don’t want this, and given this isn’t the default, it would make sense for this to be an option for amplitude integration. If it’s toggled to true, then you set the transport to beacon.