onbeforeunload onunload performance.navigation.type not working properly

1.2k Views Asked by At

I have reactjs application, I am trying to show the alert on the browser close.but some inconsistent behaviour is coming. Sometimes it is not firing the alert on the browser refresh but sometimes it is showing the alert.Below is my code:-

window.onbeforeunload = () => {
    let msg =undefined;
     if (window.performance && performance && performance.navigation.type == 1){

     }
     else{
         msg ='Are you sure?';
     }
    return msg;
};
 window.onunload = () => {
        if (localStorage.getItem('state')) {
            localStorage.removeItem('state');
        }
    }

Now sometimes it showing the alert on browser close button click, but sometimes it closing the browser without any warning, also some time on refresh alert is coming which is not expected in my scenario.I want to show the alert only on the close of the browser.Please assist me how can I handle this scenario.Many duplicate questions like this is also present in StackOverflow but all answers are old and they are not using the modern browser concept.

1

There are 1 best solutions below

0
On

You can't detect if the user wants to reload or if they want to change the page within the window.onbeforeunload or window.onunload events.

The PerformanceNavigation API only tells you how the user went to the current page, not how they will navigate to the next page on window.onbeforeunload or window.onunload events.