Attempting to execute a synchronous delete operation in Angular 6 upon the browser closing event, specifically the beforeunload or unload event

Is there a way to update a flag in the database using a service call (Delete method) when the user closes the browser? I have tried detecting browser close actions using the onbeforeunload and onunload events, but asynchronous calls do not consistently work for me. Sometimes it works fine in debugging mode, but on higher environments it fails.

After attempting synchronous requests, I discovered that Chrome now prevents synchronous XHR during page dismissal or when the page is being closed by the user. More information can be found at this link:

I have experimented with using new approaches like XMLHttpRequest() as synchronous, fetch api, and Navigator.sendBeacon(), but unfortunately none of these options seem to work for me.

If anyone has suggestions for a working solution, please share because despite searching through various posts, I haven't found anything that works for my situation.

Thank you in advance.

Answer №1

Here are some potential solutions to address your issue. Hopefully, one of them will work for you.

constructor() {
    window.onbeforeunload = ()=>{
      //call API here
    }
  }

Add the code above to your component constructor.

Alternatively,

In my view, a more effective approach would be to create a heartbeat API that sends requests regularly to inform the server about the active session and user's online status. The server can then monitor the absence of heartbeat requests for a specific period and trigger the necessary API request (as needed upon crash).

Or,

The 'beforeunload' event is triggered when refreshing pages, closing tabs, or shutting down the browser.

@HostListener('window:beforeunload', ['$event'])
    beforeUnload(e: Event) {
        e.returnValue = false;
    }

Or,

It is not feasible to guarantee a specific function will always be triggered every time a user exits a browser page due to various reasons like browser crashes. Therefore, I am exploring other strategies, such as sending multiple API calls with necessary information before the user exits to better track their activity on the page. I will update my approach as I find a reliable solution and welcome any additional insights.

Answer №2

To interact with APIs, you can utilize the fetch API. Here is an example of the syntax:

fetch('API', {
    method: 'POST', // Other methods like GET, PUT, DELETE are also supported
    body: '',
    keepalive: true
});

If you want to learn more about the fetch API, check out: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

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 preventing ng-click from assigning a variable with the value from ng-repeat in AngularJS?

I'm currently working on a feature for an app that allows users to select font styles from Google Fonts for specific text elements. Here's the code snippet I have so far: <ul ng-init='headerFont="mono"'> <li ng-repeat=&apos ...

Encountering an Unexpected Index Error with ngFor in Angular 4/5

I am struggling to create a list of inputs and I can't seem to get ngFor to work properly. <div *ngFor="let q of questions; let i = index" class="col-3"> <div class="group"> <input [(ngModel)]="q" [class.ng-not-empty]="q.length & ...

How can I dynamically populate a select menu in HTML without the need to submit any data

Looking for help with an input form in HTML that uses a combination of input and select boxes. My goal is to dynamically populate a select menu based on the data entered into the input boxes. For example: Employee One: Jim Employee Two: John Employee Thre ...

Generating Tree Structure Object Automatically from Collection using Keys

I am looking to automatically generate a complex Tree structure from a set of objects, with the levels of the tree determined by a list of keys. For example, my collection could consist of items like [{a_id: '1', a_name: '1-name', b_id ...

Struggling to comprehend JavaScript in order to customize a Google map

I'm new to the JavaScript world and having some trouble with my map styling. The map itself is displaying correctly, but the styles aren't being applied. I keep getting an error message saying I have too much code and not enough context, so I&ap ...

Implementing raw static HTML files in webpack: a step-by-step guide

Recently, I created a basic template called test.html <div>raw text with content</div> All I'm trying to achieve is to import the raw file without any alterations For example: require('./test.html'); // This should return "&l ...

Validating dropdown lists with Jquery

Custom Dropdownlist: <div class="col-md-2"> <div class="form-group"> <label for="field-3" class="control-label">Priority</label> <select id="lstpriority" class="custom-selectpicker" data-live-search="true" da ...

Incorporating an external SVG link into a React application

While I may not be an SVG expert, I haven't encountered any issues with loading SVGs in my React app so far. I prefer using the svg tag over the image tag because sizing tends to present problems with the latter option when working with external links ...

Update the image on a webpage within a template using AJAX code

I manage a website that utilizes templates. Within the template, there is a main image that I need to replace on specific pages, not throughout the entire site. I am seeking a way to change this main image to a new one on select pages using Ajax. Upon re ...

Why does a React error keep popping up when trying to set a background-image in my CSS?

I've been working on my React project and I can't figure out why I keep encountering this error. I double-checked the URL paths and made sure they were named correctly, yet the error persists. Here is a snippet of my CSS: background-image: url ...

Tips for connecting Vue data to a dropdown menu

While diving into Vue.js, I'm encountering a puzzling issue. Despite receiving data from the server (5 records), it's not populating the <select> element properly. Instead of multiple options, all I see is a single one displaying {{dept.DNa ...

Utilizing Angular Material to emphasize a row in a table upon clicking

Guide on Applying a "Highlight" Effect to a Row When Clicked - Angular 8 Below is the structure of my table: <ng-container *ngIf="videos$ | async as videos"> <mat-table [dataSource]="videos" *ngIf="videos.length"> <ng-container matColu ...

What is the process for customizing the appearance of a prop within the <TextField> component?

Using my custom DatePicker.js component, I have two instances of <TextField>. When the user clicks on the <CalendarIcon> within the <TextField>, a small calendar pops up. However, I want to style the label in the <TextField> in a sp ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Implementing a watcher property in JavaScript to dynamically add a class to an element

I'm currently facing an issue where I need to apply a class to an element when a certain data property changes. My approach involves using a watcher to monitor the value change and adding a class through JavaScript, as demonstrated in the code snippet ...

How can I effectively monitor and manage updates in my Vue app that is performing CRUD operations?

In my current project, I am developing a Vue application that utilizes Vuex to retrieve objects from an API. These objects are displayed in tables with paging functionality and are retrieved in batches from the API, sometimes containing nested entities. Th ...

`Is there a way to modify the zAxis of a Paper component in Material-UI?`

Hello, I am curious about how to change the z-axis of a paper from MUI. https://i.sstatic.net/iKXLG.jpg The issue I'm facing is that the carousel is overlapping my menu and I need the menu to be on top of everything. Here is how I have it structure ...

Exploring the asynchronous nature of componentDidMount and triggering a re-render with force

I am puzzled by the behavior in the code provided. The async componentDidMount method seems to run forceUpdate only after waiting for the funcLazyLoad promise to be resolved. Typically, I would expect forceUpdate to wait for promise resolution only when wr ...

What is the best way to handle sequential $http calls in AngularJS? Specifically, I want to make the second $http call dependent on the response of the first

When making two $http calls, the second call should only be executed based on the response from the first call if there is an error present. ...

Angular Routing can be a powerful tool for managing multiple article posts in an efficient and organized way

I am in the process of building a website with Angular that features numerous articles. Whenever a user clicks on an article, I want it to navigate to a new URL using routing. To achieve this, I have created a new Article component and here is how my app- ...