I am building an Angular Application which has Login & Logout Functionality. On click of logout the user status is updated in the Database using Laravel API, but I need to handle the browser close condition, If user closes the browser, then I need to update status in the Database, but i dont know how to call Laravel API on browser close. Any help is appreciated.
Asked
Active
Viewed 3,229 times
1
-
There are events you can listen to and act accordingly: https://stackoverflow.com/questions/37642589/how-can-we-detect-when-user-closes-browser – monogate Jun 30 '18 at 08:41
-
Are you talking about Laravel events or Angular events ?, because Angular events not called when browser close – pradip shinde Jun 30 '18 at 08:45
2 Answers
2
You can try with this solution
add window:beforeunload
event
import { Component , HostListener } from '@angular/core';
export class AppComponent {
@HostListener('window:beforeunload', ['$event'])
doSomething($event) {
/// code
}
constructor() {}
}

Krishna Rathore
- 9,389
- 5
- 24
- 48
-
Hi, is it enough if I put this in app.component.ts? Or do I have to put this method in every component? – Usr May 22 '19 at 09:12
-
1
0
Add ngOnDestory
life cycle hook in your AppComponent
(your root component).
export class AppComponent implements OnInit, OnDestory {
...
ngOnDestory() {
// API Call
}
...
}
According to Angular.io documentation, ngOnDestory
is lifecycle hook that is called when a directive, pipe or service is destroyed.

Vala Khosravi
- 2,352
- 3
- 22
- 49
-
1Is this ngOnDestory() hook will call on browser close?. Because as per my knowledge these Life cycle hooks are used only when we are in application. – pradip shinde Jun 30 '18 at 10:22
-
1
-
did you tried `onbeforeunload` ? https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onbeforeunload – Vala Khosravi Jun 30 '18 at 11:47