1

I can't use sendBeacon as I need to send Bearer token and it seems that the only header you can send with sendBeacon is content type.

I have a user who has a presence which is either "AVAILABLE", "IN CALL" or "DO NOT DISTURB". My problem is that right now, if the user is "IN CALL" and then they exit the browser or close the tab, their presence doesn't change from "IN CALL" to the default "AVAILABLE". Then if they load the website again, their status is still "IN CALL" even if they aren't in a call anymore.

This is why I decided to add a beforeunload event listener in the componentDidMount() that makes a POST request to the back-end in order to change the presence to the default "AVAILABLE". My first problem was that most of the time, the POST request wouldn't get through. I assume the request didn't go through because it was racing with the closing browser, and losing.

My question is how can I make it 100% sure that the POST request will get through before the browser/tab closes?

Currently I'm working with this:

componentDidMount() {
  window.addEventListener('beforeunload', this.onBeforeUnload);
}

And:

  onBeforeUnload = (event) => {
    try {
      const headers = {
        Authorization: `Bearer ${getAccessToken()}`,
        'Content-Type': 'application/json',
      };
      const defaultPresence = {
        presence: 'AVAILABLE',
        message: '',
      };
      const url = getServerURL() + urls.PRESENCE;

      fetch(
        url,
        {
          method: 'POST',
          headers,
          body: JSON.stringify(defaultPresence),
        },
      );
    } catch (error) {
      console.log(error);
    }
  }
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • Is sendBeacon without a token that much of a security risk? What's the worst thing that could happen? –  Jun 08 '21 at 09:13
  • Also: https://stackoverflow.com/questions/4945932/window-onbeforeunload-ajax-request-in-chrome –  Jun 08 '21 at 09:14
  • @ChrisG The back-end requires it and I can't make any changes on the back-end. – Onyx Jun 08 '21 at 09:15
  • When you close a codesandbox.io tab with unsaved content the browser is showing an alert asking you to confirm leaving the page, maybe starting an async request and then triggering the alert will work? –  Jun 08 '21 at 09:28

0 Answers0