简体   繁体   中英

React.JS confirmation only when closing tab / browser, not when refreshing

Is it possible to get an alert/ confirmation only when closing the tab/browser? Every time that I'm refreshing the page/getting an alert this confirmation comes up, and I don't want it to act like that. I created a boolean State variable- if it's true- the confirmation should pop up, false- shouldn't:

render(){
        window.addEventListener("beforeunload", (ev) => 
        {  
          if(this.state.hasChanged===true)
           {
                ev.preventDefault();
                return ev.returnValue = 'Are you sure you want to close?';
           }
}

I also tried:

render(){
        window.addEventListener("beforeunload", (ev) => 
        {  
            console.log(performance)
            if((performance.navigation.type!==1)&&(this.state.hasChanged===true))
            {
                ev.preventDefault();
                return ev.returnValue = 'Are you sure you want to close?';
        }
        });
}

Thanks!

From this answer

The way beforeunload works, you can not differentiate weather it's a page refresh or a browser close. beforeunload it is a quite confusing event avoid using this.

Hence for cases where you are dealing with the session you should use session storage. The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).

So I guess you can somehow manipulate session storage. Hope this helps.

I think I understand the question. If you're trying to display a message before the user leaves the page you can use the event found in the window object called onbeforeunload. You can find the document for that on MDN (linked below). I hope that helps.

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

This can be used to make those “Are you sure you want to leave” messages.

And so the browser doesn't accidentally reject the alert you can use a Toast or Lightbox instead.

-Good luck!

@Davo like he said, manipulating localStorage might be the best thing to do. So if the user comes to your page add whatever localStorage item you want. You could even do it in a time format so that you can have it expire. You can also validate the token on every page you render just to make sure that the user has the token. So if the user has that same token that you created then you can manipulate your state from there. Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM