How to send API request on browser/tab close?

Viewed 572

I am trying to send API request while closing tab/browser, I have tried unload and beforeUnload handler, but It does not work, I am guessing that API call not occurring because tab/browser closes instantly, and there isn't enough time to make request, everything is working during testing with debugger keyword, but doesn't without. Any Idea how can I make a call before closing tab/browser?

My code below

component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'admin-frontend';

  constructor(private loginService: LoginService) {}

  ngOnInit() {}

  @HostListener('window:unload', ['$event'])
  unloadHandler(event) {
    if (!!this.loginService.currentUser) {
      this.loginService.logout({});
    }
  }

  // вызов логаут когда клиент закрывает браузер или окно
  @HostListener('window:beforeunload', ['$event'])
  beforeUnloadHandler(event) {
    if (!!this.loginService.currentUser) {
      this.loginService.logout({});
    }
  }
}

service.ts

    logout(params) {
        return this.post('user/logout', { ...params }, true).subscribe(_ => {
            this.applicationId = null;
            this.userData.next(null);
            this.loginFacade.userData.next(null);
            this.storage.clear();
            this.user = undefined;
            this.router.navigate(['login']);
        })
    }

core.service.ts

  post<T>(url: string, param: any, withHeader: boolean = false): Observable<T> {
    if (withHeader) {
      const headers: HttpHeaders = new HttpHeaders({
        SessionId: this.user.sessionId,
      });
      return this.http.post<T>(`${this.apiUrl}/${url}`, param, {
        headers: headers,
      });
    } else {
      return this.http.post<T>(`${this.apiUrl}/${url}`, param);
    }
  }
1 Answers

Hi you can use this function to detect browser close

window.onbeforeunload = function () {
    return "Do you really want to close?";
};
Related