2

I am trying to send a POST HTTP request before browser close.

Basically I'm trying to event out the user action that they've closed the page, but the call isn't making it out of the app before it shuts down.

I am under the impression that this isn't possible with a normal HTTP request because the fact you must subscribe to the HTTP request.

I've tried the following solution found here: Angular 2 - Execute code when closing window

This won't work for me as I'm not doing simple GET. Here's what I've got so far.

component.ts

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

service.ts

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

Is there a way to utilize XMLHttpRequest() like the solution above states? What other options are there for a solution like this?

Any help is appreciated.

thenolin
  • 1,013
  • 3
  • 10
  • 28
  • Possible duplicate of [Trying to detect browser close event](https://stackoverflow.com/questions/20853142/trying-to-detect-browser-close-event) – Keenan Diggs Jul 03 '19 at 19:15
  • this sounds nefarious.... – Blair Holmes Jul 03 '19 at 19:21
  • [`navigator.sendBeacon()`](https://stackoverflow.com/a/47108290/43848) is the answer for javascript in general, disregarding Angular or any other framework – artem Jul 03 '19 at 19:22

1 Answers1

0

I am facing the same issue because Chrome now disallows synchronous XHR during page dismissal when the page is being navigated away from or closed by the user.

https://www.chromestatus.com/feature/4664843055398912

I search everywhere and found that synchronous calls is only the solution but how? as this type of calls are deprecated.