-1

I have an application which needs to make sure the user has saved their data when they accidentally close the browser (or tab). I have added a window:beforeunload handler to show the confirm dialog and a window:unload to call an http service call if the user really did want to leave but save the changes. However, I the call never gets executed on the server (unless I set a break point chrome). I found a post using angularjs (How to send an HTTP request onbeforeunload in AngularJS?) but cannot for the life of me figure out how to do this in Angular 5. Any help would be much appreciated.

KenPx
  • 39
  • 7

1 Answers1

2

I have figured it out with a bit of help from a different post (Angular 2 - Execute code when closing window).

So to save my info I use a post like the following...

let xhr = new XMLHttpRequest()
xhr.open("POST", url, false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
KenPx
  • 39
  • 7
  • This works no longer because of removing the async flag and defaults to true in Chrome, so it leads to an error if you try to do it in window.unload – JohnnyDevNull Feb 12 '20 at 08:16
  • Any suggestions then? – KenPx Feb 13 '20 at 13:02
  • The only thing you can do is to make a call in the ngOnDestroy in the AppComponent itself, there is no way left to do a sync call in unload handler – JohnnyDevNull Feb 14 '20 at 19:55
  • Maybe this could be a try https://usefulangle.com/post/62/javascript-send-data-to-server-on-page-exit-reload-redirect ... "Method 3 - Using navigator.sendBeacon to Send Data Asynchronously to the Server" – JohnnyDevNull Feb 14 '20 at 19:58
  • Thanks I will look into sendBeacon! – KenPx Feb 17 '20 at 13:31