0

I am building a web app and one of the functionalities is to trigger an action in the backend which can take up to 5 minutes. This 'action' is a process which will run totally on its own (regardless of the front-end/back-end of my web app).

There is a form on the client-side which I use JavaScript to grab the data, clean it up/validate and send an Ajax call to my backend to start the process (which can take up to 5 minutes).

My question is, what if the user refreshes the page? The backend will still be triggered and run on its on, but I wanted to be able to capture the response back to the browser once the process is done in the back end. Is that viable/possible?

My Ajax is a pretty simple POST request to my backend:

$.ajax({
    type: 'POST',
    url: '/add-user',
    data: {'data': JSON.stringify(data)},
    //contentType: 'application/json;charset=UTF-8',
    success: function(response){ 
        console.log(response['message'])
    }
    //timeout: 3000 // sets timeout to 3 seconds
});
h4v3st
  • 17
  • 6
  • [`window.onbeforeunload`](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload) runs a function every time the user refreshes or leaves the page. – Rojo Aug 20 '21 at 00:07
  • 2
    You could look into the [Notification API](https://developer.mozilla.org/docs/Web/API/Notifications_API/Using_the_Notifications_API) which can push the results to the client even if they've left your site. (You *do* need to ask the user permission to send them notifications) – Stephen P Aug 20 '21 at 00:09
  • @Rojo How does that help? They don't want to do something when the user leaves, they want to do something when the action finishes 5 minutes later. – Barmar Aug 20 '21 at 00:34
  • What happens to the success: response from the Ajax call if the user refreshes the page? That's just lost and I have to manage to send the actual response from backend to frontend? – h4v3st Aug 20 '21 at 01:51

1 Answers1

0

Please refer to this question prompt-user-before-browser-close

The only solution is to display a loading bar or spinner on the page while your page is waiting for the server task to finish.

If the user wants to navigate away you can use the confirm prompt.

I highly suggest using a websocket connection and if the user really closes, then inside window.onbeforeunload you should send a message and notify the backend to cancel the request context and stop the task from running. Running something like this without this protection can make your backend easy to get bombed.

PS. If it's a process independent of your backend then you should have scripts in place to kill it if the request context is canceled.

Mihai
  • 82
  • 1
  • 6