When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now
Today I had the same problem and found a possible solution that I want to share with you.
While thinking about what could help to discern between refresh and close, cookies came to my mind. I remember that setting a cookie without an explicit expiration date, renders it available only for the current session. And a current session is clearly valid until the browser is closed. This does not include closing a tab, but my problem was about user authentication and I didn't want to logout the user only for having closed a tab (I think that's the same approach as the ASPXAUTH
cookie of ASP.NET).
So, I put a simple cookie in the document.cookies
collection when user logged in and checked it on page load: if cookie was still there it was a refresh or a reopened tab and user data was kept, if cookie was not present session had expired so user data was cleared (same as an explicit logout).
Hope this approach can be useful to someone else!