hdw3
hdw3

Reputation: 951

How can I send request to backend when user closes/refreshes browser?

What I am trying to achieve:

I have a lobby which is updated automatically so if any player leaves, others can see it right away. When player quits I send a request to backend to kick him out of the lobby and after that I "poke" the lobby, which was left by the player, using sockets so this lobby can update itself and display actual list of players.

My problem

I have no idea what to do when one of the players in the lobby closes tab/browser, refreshes or types address of some website. At first I wanted to use beforeunload event but I only managed to get confirmation from user whether he really wants to leave or not. Unfortunately I couldn't find any info how to check what was the user's action (leave or stay).

  @HostListener('window:beforeunload', ['$event'])
  unloadNotification($event: any) {
    // if shouldnt be closed ask for confirm
    if (!this.canDeactivate()) {
      $event.preventDefault();
      $event.returnValue = true;
    }
    // it would be ideal for me if something like this was possible
    // but according to what I have read so far, browsers dont allow checking user's response
    // for this event
    if(userDecidedToLeave){
      this.cleanUp(); // sends request to backend to kick player from lobby
    }
  }
}

Then I decided to take "the easy way" and simply skip user's confirmation when leaving and just use ngOnDestroy() but either ngOnDestroy() is not called when user closes tab/browser, refreshes, types address of some website or it is impossible to send requests from ngOnDestroy() in this scenario. (or some other reason I couldn't think of).

  ngOnDestroy() {
    // if user left the lobby
    if (!this.canDeactivate()) {
      this.cleanUp(); // send request to backend to kick user from the lobby and then update lobby
    }
  }

Upvotes: 1

Views: 624

Answers (1)

user11412058
user11412058

Reputation:

Since you use Web sockets, you can check each user at regular intervals to see if they are currently online. Doing so would be more appropriate for the following use-cases:

  • The user can simply reload the page. In this case it is not necessary to show him a confirmation dialog or kick him out of the chat because he will be right back.
  • His browser might get closed unexpectedly (e.g. browser crash, or if he uses a mobile browser, he can exit the browser app at any time he wants, etc.)

Otherwise, as far as I know, it is not possible to achieve this kind of task only with JavaScript (i.e. via the beforeunload event, etc.).

Upvotes: 2

Related Questions