0

I know there are answers regarding this, but it doesn't encompass some of the edge cases. I have to ensure to make a HTTP request before a user leaves a page. There are a couple of ways for users to do this:

  • Closing the tab
  • Clicking on an external link
  • Closing the browser
  • Shutting down the computer(for whatever reason, power outage, etc)

Any reliable way to do this? Any work arounds? Doesn't need to be javascript but any slick/hacky ways to accomplish this? I guess I can make intervals to run to make requests time to time to at least capture some data, but any other thoughts?

inertia
  • 3,997
  • 2
  • 17
  • 26
  • I doubt you can do an HTTP request in case of power outage – Cid Oct 04 '19 at 15:09
  • 1
    Possible duplicate of [How to Detect Browser Window /Tab Close Event?](https://stackoverflow.com/questions/21227383/how-to-detect-browser-window-tab-close-event) – Cid Oct 04 '19 at 15:10
  • 1
    Isn't the only option of doing this onbeforeunload? It is not possible to account for power outage unfortunately, you will have to send periood requests and deduct that the client is dead in the server side if you really want to account for that – sinanspd Oct 04 '19 at 15:11
  • Hmm.. Any work around for this? I guess I can create a set interval to make requests that way... but I just wanted to know if there was a more slick way to do this. – inertia Oct 04 '19 at 15:17

1 Answers1

0

Shutting down probably wont work. But you could probably try:

window.addEventListener("beforeunload", function (e) {
  (e || window.event).returnValue = 0; //Gecko + IE
  return 0;                            //Webkit, Safari, Chrome
});

If you have a backend then maybe you could open a websocket and do the http request there on disconnect.

estavillo
  • 139
  • 10
  • As far as im aware, most modern browsers don't really support much functionality being called with the beforeunload event is called because of all the malicious popups that used to take advantage of it – Captain Squirrel Oct 04 '19 at 15:19