Click here to Skip to main content
15,917,481 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I am working on a react project. My requirement is to clear redux store when ever the use closes the browser. (Not on Refreshing the page.)

i have done some research on it and found about EventListner events "beforeunload".
Here what i have tried.

_props.ActionSessionClear() : clears my redux state.
Every things works fine but it clears my redux state when ever i refresh the page.
And another issue is when i try to close the tab(chrome), it prompts me leave page? and even if i click on cancel, it clears my Redux State.
In IE it behaves Differently.

My requirement is just to clear the redux state. i dont need any message before closing the tab or refreshing the tab. I dont wann clear state on page refresh.

Is there any other approach to do the same??
A quick suggestion would be appreciated. Thank you!!!

What I have tried:

componentDidMount() {
    window.addEventListener("beforeunload", this.callEvent);

componentWillUnmount() {
      window.removeEventListener("beforeunload", this.callEvent);

callEvent = e => {
    const _props = this.props;
    var confirmationMessage = "o/";
    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Webkit, Safari, Chrome
Updated 25-Mar-20 6:36am
ZurdoDev 24-Mar-20 12:53pm    
No, I have never seen a solution that works in all cases. The beforeunload is the only option that I am familiar with.

1 solution

If you return a value from the beforeunload 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 unload 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 sessionStorage instead of localStorage.

Window: beforeunload event - Web APIs | MDN[^]
Window: unload event - Web APIs | MDN[^]
Window.sessionStorage - Web APIs | MDN[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900