1

Actually, I want to update a flag in Db using a service call(Delete method) once the user close the browser. I am able to detect browser close action using onbeforeunload and onunload events but async call doesn't work for me(sometimes in debugging mode it works fine but on higher env it doesn't work).

Then, I tried to make sync request but then I found that Chrome now disallows synchronous XHR during page dismissal when the page is being navigated away from or closed by the user. check link : https://www.chromestatus.com/feature/4664843055398912

I have tried new XMLHttpRequest() as sync, fetch api also Navigator.sendBeacon() but unfortunately nothing works for me.

Please suggest something which works because I have visited so many posts but nothing works for me.

Thanks in advance.

kae_screechae
  • 169
  • 12

2 Answers2

0

I have some solution for this. Hope so any one of them solves your issue.

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

In your component constructor write above code

OR

In my opinion the better idea is making the heartbeat api that sends requests every N seconds to notify server that the session is active and the user is online. On the server check every M minutes if there was no heartbeat requests for more than N seconds: if it is so - execute the API request(what you wanted to execute on crash).

OR

'beforeunload' would be trigger when refreshing pages, closing tab, or closing the browser.

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

OR

It is not possible to ensure that every time an user exits a browser page a specific function will be triggered. The reason is that the browser could close the window for many reasons. Yes it could be a user action but this is not the only case. For example The browser could crash.

In my case I will have to find another strategy to track the time the user stays on the page. For example I am planning to send a lot of API calls before the user exits with all the informations I need to understand his stay on the page. I will update the answer when I will reach a good solution. Anyway I will still wait for better answers.

Sanjay Lohar
  • 520
  • 2
  • 8
  • Thanks for the reply. Actually, I am clear about the scenario in which I need to execute this service call but my issue is with the how I can make this call successfully so that it will call the api in sync way. – Vivek Joshi Mar 05 '20 at 07:00
0

You can use the fetch API. The syntax would be:

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

Just an additional read: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

fcdt
  • 2,371
  • 5
  • 14
  • 26
Anubhab
  • 1
  • 2