Search code examples
javascripteventscookiesbrowserwindow

Check if beforeunload is caused by closed tab/window or refresh


I am trying to bypass chromes "Continue from where you left off" session cookie issue, where cookies are not destroyed after closing browser window / tab.

To do this I have added an beforeunload listener to the window, that fires a function to remove a cookie:

window.addEventListener('beforeunload', destroySession)

However this also destroys a cookie when I refresh the page or click on "go back" buttons in the browser, so I need sub sequential checks in my destroySession function to see what caused beforeunload to happen.


Solution

  • The short answer is - You can't.

    The long answer is - You can setup a convoluted way of "detecting" a refresh vs being opened in a clean tab or window BUT (there is always a but) note that is is not perfect and each method comes with it's own set of issues (I HIGHLY DO NOT recommend using them): Check if page gets reloaded or refreshed in Javascript