Is there a way to trigger a request to the backend when the user closes or refreshes the browser?

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
    }
  }

Answer №1

If you are utilizing Web sockets, one way to monitor online users is by checking their status regularly. This approach is particularly useful for the following scenarios:

  • When a user simply refreshes the page, there's no need to display a confirmation dialog or remove them from the chat since they will return shortly.
  • In situations where the user's browser unexpectedly closes (such as a crash or intentional exit on mobile browsers), it is important to keep track of their online presence.

Without relying solely on JavaScript (e.g., using the beforeunload event), achieving this level of functionality may not be feasible.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for integrating an extension function into an Express response using TypeScript?

I am looking to enhance the Response object in Express by adding custom functions. Specifically, I want to introduce a function: sendError(statusCode: number, errorMessage: string) which can be called from anywhere like this: response.sendError(500, &qu ...

Encountered an error with create-react-app and MaterialUI: Invalid hook call issue

I am encountering an issue while trying to set up Create-react-app with Material UI. The error message I receive pertains to Hooks. Could there be something else that I am missing? This is the specific error message being displayed: Error: Invalid hook ...

Instructions for inserting a hyperlink into a column of a table with the *ngFor directive in Angular2

I currently have a table with 4 columns: Name, ID, Department, and City. I am fetching both the row data and column data as an array from a TypeScript file and iterating through them using *ngFor. Below is a snippet of my code: <tbody> <tr *ng ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

The functionality of the System JS map is not functioning properly

Despite the challenges I face with System.js, I find it to be a valuable tool that I prefer over alternatives. This is my current System.js configuration: System.config({ packages: { app: { format: 'register' ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...

SolidJS directives utilizing use:___ result in TypeScript errors when used in JSX

As I work on converting the forms example from JS to TS, I came across a typescript error related to directives in HTML: It appears that validate and formSubmit are being recognized as unused variables by typescript, resulting in the following jsx error: ...

What steps should I take to transition from using require statements to imports with typescript in my mocha tests?

I have the following values in my package.json file: "scripts": { "test": "mocha -r ts-node/register security.test.ts" }, "type": "module", . . ...

What is the method for determining the type of search results returned by Algolia?

My connection between firestore and algoliasearch is working well. I am implementing it with the help of typescript in nextjs. I am attempting to fetch the results using the following code snippet products = index.search(name).then(({hits}) => { ret ...

Enhance your FullCalendar experience with React by displaying extra information on your calendar

I am new to using React and FullCalendar, and I have a page layout similar to the image linked below. Additionally, I have a list of events structured as shown: id: "9", eventId: "1", title: "Training Network", st ...

Issue with updating state in child component preventing addition to state

Recently, I made the switch to TypeScript in my NextJS project using Create T3 App. One of the components in my app involves updating the state after a Prisma mutation is performed. I attempted to pass the setItems (which was initialized with useState) to ...

Exploring the world of dynamic form creation using Angular and Mat-select options

I'm working on an Angular application and I want to create a dynamic form using Mat-select for the type selection. Depending on the chosen type, I need to be able to add or remove fields dynamically. I also want to display a specific field if the typ ...

What are the most optimal configurations for tsconfig.json in conjunction with node.js modules?

Presently, I have 2 files located in "./src": index.ts and setConfig.ts. Both of these files import 'fs' and 'path' as follows: const fs = require('fs'); const path = require('path'); ...and this is causing TypeScr ...

Utilizing JSDoc for establishing an index signature on a class in ES6

When working with JSDoc, achieving the equivalent of Typescript's computed property names can be a challenge. In Typescript, you'd simply define it like this: class Test { [key: string]: whatever } This syntax allows you to access these comput ...

Navigate through Angular Material rows by utilizing the up and down arrow keys

I customized my mat-table by adding an ngclass to make the rows clickable. Now, I want to enable users to navigate using the arrow keys. Referring to this GitHub issue (https://github.com/angular/components/issues/14861), I managed to make it work initiall ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

ng2-auto-complete automatically selects default option on a reactive form

I'm currently integrating https://www.npmjs.com/package/ng2-auto-complete into my Angular 5 application and here's how my input is set up: HTML: <input id="shipper" type="text" class="form-control" for ...

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

Angular library generation causing circular dependencies

Modification Required It has come to my attention that the issue of a circular dependency arises solely when utilizing a production build - ng build lib --prod My task involves creating an Angular library intended for utilization in a separate Angular pr ...

Mapping an array in Typescript using Angular to instantiate a class

I have received data from a web API that resembles the structure below. I am looking for guidance on how to properly map the product array into individual Products. My main objective is to convert the eating_time values into JavaScript datetime format. Cu ...