1

I am using Fetch API in my angular JS app to run a service right before the user closes the browser. What this service does is to free up a record which was locked by a user and which remained unlocked because user accidentally closed the browser. The fetch method runs just fine and it unlocks the record when I test it locally. However it doesn't work for me when I test it on the server after deployment. Also it works for some of the my teammates and doesn't work for some on the same server. The following is the method which I am calling on page unload.

var runService  = function (id) {
      var url = '/service/to/run/' + id;
      return window.fetch(url, {
        method: 'POST',
        keepAlive: true,
        headers: {
          'Authorization': 'Bearer token' + getSessionValue('access_token')
        }
      });
    }

I have tried for days now, to make it work by adding/removing parameters, but still no success. I tried to use sendBeacon, but that doesn't work either. I am writing this question after all the efforts that I could do. I would be very grateful if anyone can point me to the right direction.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Rash
  • 300
  • 1
  • 3
  • 19
  • It is rare that in some cases it works, but not in others. What is the error you get? – Marlonchosky May 05 '20 at 21:54
  • @Marlonchosky, I don't get any error, I believe it's not getting to the point where it can execute the service. I don't see the service call in Fiddler. – Rash May 05 '20 at 22:01
  • Ok, but does the code get to run on the page unload? You have tried printing in console to validate if it reaches the page unload event? @Rash – Marlonchosky May 05 '20 at 22:04
  • Yes it does. When I debug, I can step through the code and it runs perfectly fine locally. The service is also called properly. – Rash May 05 '20 at 22:07
  • What does this have to do with C#? – Guy Incognito May 05 '20 at 22:26
  • 2
    Anyway, the browser doesn't wait for the request to complete before closing the window. If the request happens quickly (like on localhost) it might go through. See [JavaScript, browsers, window close - send an AJAX request or run a script on window closing](https://stackoverflow.com/questions/6162188/javascript-browsers-window-close-send-an-ajax-request-or-run-a-script-on-win) – Guy Incognito May 05 '20 at 22:28

0 Answers0