Skip to content
Advertisement

Tell PHP backend that browser has closed from frontend Angular [closed]

I have an Angular project that communicates with a backend project made with PHP and ZF3.

I would like to know what’s the best way to tell the backend project that the browser was closed?

I had thought of sending an http request when the event beforeunload is fired but the request is canceled even if I use async/await.

The other way I thought is using websocket connection, but it seems very complex to implement in PHP just to know when the user left the browser.

Any ideas? Thanks!

Advertisement

Answer

Best way is to use the sendBeacon method:

Simple example:

window.addEventListener('unload', () => {
  navigator.sendBeacon('url/to/backend');
});

Because you use angular, you can place this on your AppComponent (although it might not be the right place)

export class AppComponent {
  @HostListener('window:unload')
  onUnload = () => navigator.sendBeacon('url/to/backend');
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement