I'm currently trying to make an Angular app make an API service call when the user tries to navigate away from my page. Either by closing the tab / window, or typing in an external URL.

I've tried to implement several different ways I've seen described here on stackoverflow questions, but none seem to have the desired effect. Some mention sync ajax requests which have been, or are in the process of being deprecated in onbeforeunload on Chrome. Others advise the use of XMLHttpRequests, which seem to have suffered the same fate. I have attempted the use of @HostListener('window:onbeforeunload', ['$event']), and equivalent in the HTML (window:beforeunload)="doBeforeUnload($event)", but all refuse to cooperate. I can get console.logs to show up, but the API never receives any call to logout the user. I have also used navigator.sendBeacon and, despite its function returning true, signalling that the job was sent to the browser queue, nothing ever materializes.

Currently, the logout function is this:

userLogout(): Observable<any> {
    return this.apiService.get('/Account/Logout/');
  }

Which, in turn, is a generic http get function:

get<T>(url: string, options?: { params: HttpParams }): Observable<any> {
    return this.httpRequest<T>('get', url, null, options ? options.params : null);
  }

The full url is added with the use of an HttpInterceptor. The logout function itself is working, as it is used in a menu option that works as expected when used manually. So the function should not be the problem.

All I'm attempting to do is to call the userLogout function either in a sync or async way and inform the backend that the user has left.

0 Answers