Reputation: 15
import { Component, HostListener, Inject } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls:['./home.component.scss']
})
export class HomeComponent {
User: any;
isRefreshed = false;
@HostListener('window:beforeunload', ['$event'])
onBeforeUnload(event: Event) {
console.log('isrefreshed', this.isRefreshed);
if (!this.isRefreshed) {
this.User.logout();
}
}
constructor(@Inject('User') userProvider) {
this.User = userProvider;
window.addEventListener('keydown', event => {
console.log('Key Pressed ==>', event, this.isRefreshed);
if (event.key == 'r' || event.key == 'F5') this.isRefreshed = true;
});
}
}
logout
on the close tab. but it also getting logged out when reload or refresh by the mouse.
How to handle these?Home
component?Upvotes: 0
Views: 1663
Reputation: 122
Not sure whether we have any browser-level events are available to handle refresh and reload. We can handle the scenario with session storage, We need to store some keys on the first load, and on every refresh or reload we can keep checking that key exist or not.
Let's take it we have a condition to check whether the key exists on the root component's ngOnInit method. If the key exists then it is reloaded or refreshed. If it does not exist then it is the first load and we need to save the key.
On close, session storage will be cleared.
Upvotes: 0
Reputation: 700
There's unfortunately no difference between closing the browser tab (window), or reloading / refreshing the window - it all registers as one event, which is unloading the contents of that DOM window element.
There's a few ways of handling that. One way of doing so would be binding the "beforeunload"-event in the root component (usually named AppComponent
) and then responding to that event there.... Since it's the root component it would be application wide.
Upvotes: 1