Search code examples
javascriptreactjsbrowseronbeforeunload

Alert not showing on browser close after doing reload of the browser, same issue is there in stackoverflow website also


I have to show the alert on browser close and refresh for a particular page. Below code is working for all scenario but it is failing in below scenario. 1. First, do the refresh, then the alert will come and ask for reloading, now do the reload. 2. Now click the browser close button Issue:- Now alert not coming in chrome and Mozilla browser, In Edge on refresh, alert is coming multiple time my code is:-

window.onbeforeunload = (ev) => {
    let msg;
    debugger;
    if (sessionStorage.getItem('previousPage') === 'employee') {
       return 'Are you sure you want to navigate away?If you navigate away, your information will not be saved.'
        ev.preventDefault();
    }
    return msg;
};

Please assist me how can I handle this scenario?


Solution

  • Try this, quite similar to this: Clear localStorage on tab/browser close but not on refresh:

    window.onbeforeunload = function (ev) {
        window.onunload = function () {
            let msg;
            debugger;
            if (sessionStorage.getItem('previousPage') === 'employee') {
               return 'Are you sure you want to navigate away?If you navigate away, your information will not be saved.'
                ev.preventDefault();
            }
            return msg;
        }
    };