You cannot do this.
- You cannot rely on an event happening in the browser.
- The server cannot contact the browser to find out if it is alive.
You do not control the end user browser. The user can close the browser, crash, disconnect from the Internet, disable or disable javascript, etc. Etc. Or, the user can simply enter a different URL (and after that the user can return to your page using the "Back" button and wait for the continuation of his session from your site).
Launch window.onbeforeunload starts every time the page is unloaded. Even if the user views another page of your site, therefore, a second session may be required.
source share