0

My requirement is that I need to call some API after close tab from browser in Javascript.

I have tried below code which almost everyone suggest, but that is not working every time. I have tried every possible way with below code:

window.onbeforeunload = function () {
   callClose();
   return;
};

function callClose() {
    // API call
}

I need proper reliable solution for this. Can anyone help me on this, I am stuck here.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dayanand Lande
  • 211
  • 4
  • 23
  • 1
    There are restrictions on what you can do in a `beforeunload` handler. You can't do an alert. It should just return a string -- if it returns a string, the browser will display a prompt automatically. – Barmar May 27 '18 at 14:03
  • I understand that, I just kept that alert for example, I have to call API there on place of alert. – Dayanand Lande May 27 '18 at 14:05
  • Maybe relevant https://stackoverflow.com/questions/6895564/difference-between-onbeforeunload-and-onunload?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Barmar May 27 '18 at 14:06
  • Barmar, In my case beforeunload is working but not reliable, sometimes working, sometimes not. especially when I loose focus of browser (Open another window on top of browser). – Dayanand Lande May 27 '18 at 14:15
  • You can never reliably detect a user closing his browser (tab). They might just kill the process or shutdown their computer. Or go offline. Or really anything. – Bergi May 27 '18 at 15:17
  • Losing focus on the window doesn't unload the page, it's not supposed to trigger this event. Unloading only happens when you close the window or go to a new page in the same window (including using the Back and Forward buttons). – Barmar May 29 '18 at 14:31
  • 1
    As @Bergi says, you shouldn't use this event for anything critical to the application. It's basically just for warning the user something like "If you leave without saving, you'll lose your changes." – Barmar May 29 '18 at 14:33

0 Answers0