How to make an HTTP request in Angular 7 before the browser is closed

I'm attempting to trigger a POST HTTP request right before the browser closes.

Essentially, I want to detect when the user closes the page and send a call, but the request isn't completing before shutdown.

It seems like a traditional HTTP request won't work due to the need to subscribe to it.

I experimented with a solution from this source: Angular 2 - Execute code when closing window

However, this approach is not suitable for my requirements as I am working with more than just a simple GET request. Here's what I have attempted so far.

component.ts

@HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler($event) {
    this.eventsService.sendEvent(this.form.value).subscribe(() => {
      console.log("Request sent successfully");
    });
  }

service.ts

sendEvent(userData): Observable<any> {
    return this.http.post<any>(this.url, userData,
      {
        headers: new HttpHeaders({
          "Content-Type": "application/json"
        })
      })
  }

Is it possible to implement XMLHttpRequest() as suggested in the above solution? What are some alternative options to achieve this functionality?

Any assistance will be highly appreciated.

Answer №1

I'm encountering a similar issue because Chrome has started to prevent synchronous XHR requests when a page is being navigated away from or closed by the user.

I've searched extensively for a solution and it seems that synchronous calls are the only option, but how can I implement this considering they are now deprecated?

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

Tips for using conditional rendering with React and TypeScript

Issue with Conditional Rendering in TypeScript It seems like I might have encountered a problem with the way I declare my components. Take a look at this TypeScript snippet: import React, { FunctionComponent } from 'react'; export const Chapte ...

Sending information from a component to a route in Angular2

Is it possible to transfer data from one component to another without displaying it in the URL during routing? Currently, I am passing data using route parameters like this: { path: 'edit-tags/:type/:name/:id', component: EditTagsCompon ...

What could be the reason my custom validator is not functioning properly and how can I troubleshoot it?

I'm currently working on creating an angular reactive form with a unique ID input field requirement. If the submitted ID already exists, I need an error message to display on the angular HTML front end. To achieve this, I am implementing logic to chec ...

Achieve a seamless redirection to the 404 component in Angular without altering the browser URL, while ensuring that the browsing

Whenever my backend sends a 404 error (indicating that the URL is valid, but the requested resource is not found, such as http://localhost:4200/post/title-not-exist), I need Angular to automatically redirect to my NotFoundComponent without altering the URL ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Tips for utilizing buttons with the antd framework in Visual Studio Code

When using the Button and Input components from antd in vscode, I encountered an error specifically with the Button component and I am curious to understand why it is happening. Interestingly, when I tried using the Input component, it did not show any er ...

Angular 7 router navigate encountering a matching issue

I created a router module with the following configuration: RouterModule.forRoot([ {path: 'general', component: MapComponent}, {path: 'general/:id', component: MapComponent}, {path: '', component: LoginComponent} ]) Sub ...

What could be the reason it's not functioning as expected? Maybe something to do with T extending a Record with symbols mapped

type Check<S extends Record<unique, unknown>> = S; type Output = Check<{ b: number; }>; By defining S extends Record<unique, unknown>, the Check function only accepts objects with unique keys. So why does Check<{b:number}> ...

What could be causing the HTTP response Array length in Angular to be undefined?

Currently, I am facing an issue while retrieving lobby data from a Spring Boot API to display it in my Angular frontend. After fetching the data and mapping it into an object array, I encountered a problem where the length of the array turned out to be und ...

Implement a class attribute to the parent <div> element using React and TypeScript

I'm trying to figure out how to achieve this task. I need to assign a class upon clicking on an element that is not directly in my code, but rather in one of its parent elements. My initial thought was to accomplish this with jQuery using the followi ...

How is it that the chosen attribute functions for every ng-container?

I have 2 ng-containers. When I am in one view, I want "My Appointments" selected in the options dropdown when navigating to that view. In the other view, I want "Active" selected in the options dropdown. Here is my html code: <div class="wrapper w ...

The state data is not being properly updated and is getting duplicated

While developing a loop to parse my API data, I encountered an issue where the values obtained were not being captured properly for dynamically loading corresponding components based on their characteristics. The problem arose after implementing useState() ...

Error in Typescript: Draggable function is undefined

I'm currently working with typescript alongside vue and jquery ui. Encountering the error "TypeError: item.$element.draggable is not a function". What am I doing wrong in my code? I have already included jquery-ui, as shown in the following files. M ...

Explaining the concept of SwitchMap in RxJS

Currently, I am utilizing Restangular within my Angular 5 project. Within the addErrorInterceptor section, there is a code snippet that invokes the refreshAccesstoken method and then retrieves the new access token in the switchMap segment. My approach invo ...

How can I bypass additional ngIf checks in the Angular template if a variable is null?

I have this code snippet in my template: <div class="icon-action" *ngIf="node == null ? false : node.data && node.data.name && !node.parent.data.virtual" (click)="delete(node)"> ...

Having trouble with Axios PUT request not sending complete data to the server using JavaScript

One issue I'm encountering is that when sending an axios request with specific data, not all of the data gets updated in the user model. Here's a look at my code: Here is the Front-End code with axios request: import axios from "axios" ...

What is the process for adding routes prior to implementing jsonwebtoken?

I am currently working with jsonwebtoken and I have some questions about how it functions. I have regular sign-in and sign-up routes that should come before the .verify function. Although I have experience using jwt in the past, this is my first time imple ...

Excess whitespace found in string within mat-option

Every time I retrieve text from the mat-option, I notice an additional space at the end of the string. This causes my assertion to fail when trying to compare it with the expected value. This issue is new to me, and I'm unsure how to address it. Why ...

Unable to attach to 'leafletOptions' as it is unrecognized as a property of 'div'

It seems like I keep encountering this problem, which is often resolved by adjusting import statements. Right now, my imports look like this: import { LeafletModule } from 'node_modules/@asymmetrik/ngx-leaflet'; import * as L from 'leaflet& ...

Can someone provide guidance on utilizing parentheses in HTML code?

I am facing an issue in my Angular project while using the WordPress API. The problem lies in the API address structure which includes "" like this: <img src="{{importantvideo.better_featured_image.media_details.sizes.["covernews-med ...