call different function during page refresh and close javascript

Viewed 321

I am creating a web app using web socket, which on user closes the tab I will make an API call to the server to clean the user related info in the server, I used onBeforeUnload listener in javascript, but this method also gets triggered during the page refresh.

I need to trigger a method only during the tab or browser close, but not during the page refresh.

I know this question has been asked several times, some solution suggested using cookies will not be helpful in my case

2 Answers

As far as I know, you can not listen to actions of browser's tab close or exits. For your application it is an "unload", whatever caused it...

The only thing I could think about is maybe add a listener for keyboard key press (F5), however it doesn't help in case someone refreshed by clicking on the browser's refresh button.

I don't know what is the use case, but most of the things should be done when a page unloads (no matter why) and/or when the page is back up again. So most of the solutions are for situations where your page is loaded again - and then you can determine what was the source of the load and make farther actions, but since you have an option were someone can close and never come back, that might not be the case.

Some solutions for page load up:

  • You can use Navigation type.
  • You can check referer.
  • You can use cookies or other types of browser storage.

I would recommend to rethink about your use case. Maybe you can do whatever you want on load up or leave it on onBeforeUnLoad without knowing the future :)

Related