Search code examples
angulartypescriptbrowsercomponentsangular5

Angular 5 - How to make an API call when user closes the browser window?


I have a tracking mechanism through which I send JSON objects to an API endpoint during the stay of an user on a web page. So I am sending API calls on some particular events. The API has to receive a call when the user leaves the page.

The problem is that I am using the functions below to trigger when the user closes the broser, but the functions are triggered only in browser debug mode.

// page-wrapper.component.ts ... // triggers on DOM unload @HostListener('window:unload', ['$event']) unloadHandler(event) { this.service.apiCall(); // this is nevertriggered console.log('unloaded DOM') // triggered only in browser debug mode } // triggers just before unloadHandler() @HostListener('window:beforeunload', ['$event']) beforeUnloadHander(event) { this.service.apiCall(); // same as above }

So I tried both the methods. If I debug them The methods seems to be triggered but the APIs do not receive anything.

I can ensure that the function that contacts the APIs was tested and it has no problems.

I think the problem is related to unloadHandler() or beforeUnloadHandler().

Does someone know how to call an api when the user closes the broser window or the browser tab?

Note: that the application could live in a standalone browser tab or an iframe.


Solution

  • Thanks to @Francesco I arrived at the following conclusion:

    It is not possible to ensure that every time an user exits a browser page a specific function will be triggered. The reason is that the browser could close the window for many reasons. Yes it could be a user action but this is not the only case. For example The browser could crash.

    In my case I will have to find another strategy to track the time the user stays on the page. For example I am planning to send a lot of API calls before the user exits with all the informations I need to understand his stay on the page. I will update the answer when I will reach a good solution. Anyway I will still wait for better answers.