My Objective:
I am working on a lobby feature that updates automatically when a player leaves. Using backend requests and sockets, the lobby is updated to display the current list of players after someone exits.
The Challenge:
I am faced with the issue of handling situations where a player closes the tab/browser, refreshes the page, or navigates away from the website. Initially, I tried using the beforeunload
event to prompt the user before leaving, but was unable to determine if the user chose to leave or stay.
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
// Prompt user for confirmation if necessary
if (!this.canDeactivate()) {
$event.preventDefault();
$event.returnValue = true;
}
// Ideally, I would like to check the user's action here,
// but it seems browsers do not allow this capability
if(userDecidedToLeave){
this.cleanUp(); // send request to backend to kick player from lobby
}
}
}
Eventually, I opted for a simpler approach by utilizing the ngOnDestroy()
method. However, I discovered that ngOnDestroy()
is not triggered when a user closes the tab/browser, refreshes the page, or navigates elsewhere. This limitation prevents me from sending requests to update the lobby in these scenarios.
ngOnDestroy() {
// Check if user has left the lobby
if (!this.canDeactivate()) {
this.cleanUp(); // send request to backend to kick user from the lobby and then update lobby
}
}