3

I need to let the server know when the user closes or reloads the page. I'm listening to the "beforeunload" event and when the function is called I'm sending an axios call to the server. It works when refreshing the page but not when closing it and I don't know how to fix it.

Here is my code

  componentDidMount() {
    window.addEventListener("beforeunload", this.endSession);
  }

  componentWillUnmount() {
    window.removeEventListener("beforeunload", this.endSession);
  }

  endSession = (e) => {
    axios
      .post(Globals.backendServer + "/session/end", {
        sessionData: this.state.sessionData,
      })
      .then((res) => {})
      .catch((err) => {
        alert(err);
      });
  };

2 Answers 2

1

There is no guarantee that asynchronous actions executed in the beforeunload event will complete, and axios uses an asynchronous way of making requests.

You can probably use good old XHR to make a synchronous request. If you go to the section labeled Adapting Sync XHR use cases to the Beacon API, they will go over strategies of keeping requests alive during unload because synchronous XHR is deprecated.

Note that synchronous HTTP requests are generally a bad idea because they will render the page unresponsive while they are completing. I'm not sure what the behavior would be for a synchronous request during unload.

Sign up to request clarification or add additional context in comments.

Comments

0

Unfortunately unload and beforunload life-cycles is not reliable for Ajax request, I prefer Handle this with token and refresh token from the server-side Even when you detect closed page,how could you define what tab or page closed when user can open multiple tab

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.