If you return a value from the
event, the browser will display a confirmation message to the user asking whether they want to leave the page.
By the time the user clicks "cancel", your code has already run, and your state has been cleared.
You could use the
event instead, which will fire just before the page is unloaded. However
, there is no way to know why that unload is happening - the user could be closing the tab, navigating to a different site, navigating to a different page in the same site, or reloading the page.
If you just want storage which will be cleared when the user closes the tab, you could use
Window: beforeunload event - Web APIs | MDN
Window: unload event - Web APIs | MDN
Window.sessionStorage - Web APIs | MDN