0

I want my application to execute some code when the browser is closed. My problem is beforeunload event that is called on both the browser close button and tab close. I don't need that code to be executed on tab close. Is there any way that we can execute that code on browser close not on tab close?

I have tried beforeunload event that is calling on browser close and tab close. I need to separate these close calls so that the same code shouldn't be executed on for browser close and tab close.

Mehdi
  • 385
  • 1
  • 12
  • 2
    Seems like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is the original usecase? What code do you want to run on window close but not on tab close? – vighnesh153 Dec 27 '22 at 08:33
  • I want to run ajax call to server for deleting session from databases – Majid Khakwani Dec 27 '22 at 08:41
  • You might be interested in [service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) and the [Broadcast Channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API). – jsejcksn Dec 27 '22 at 08:47
  • @MajidKhakwani. One way I could think to solve this would be creating [session cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_the_lifetime_of_a_cookie) and storing the last use time in the DB. Then, define some threshold for your session at the backend (maybe a week or a month?), and then auto-delete the sessions from your DB if the last-use time was above that threshold. – vighnesh153 Dec 27 '22 at 12:22
  • If you can, avoid using `beforeUnload` and `unload`, because [they're not reliable](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#usage_notes). Be sure to read the compatibility notes as well. – FiddlingAway Dec 27 '22 at 20:28

1 Answers1

1

Unfortunately it is not possible to differentiate between these events. Refer to this thread Detect browser or tab closing