skip to Main Content

I want to trigger a function when the user exits the web page by closing the browser tab or pressing the browser’s back button. Currently, I’m using the "beforeunload" and "unload" events. But when the user reloads the page the download event also fires. Is there a way to solve this?

if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {} else {
    window.addEventListener('beforeunload', function() {
        window.addEventListener('unload', function() {
            if (!isSubmit) {
                sendDownloadEmail();
            }
        });
    });

    window.addEventListener('unload', function() {
        if (!isSubmit) {
            sendDownloadEmail();
        }
    });
}

2

Answers


    1. The beforeunload event is used to capture tab closes and back button presses.
    2. The pageshow event is used to differentiate between reloads and actual page exits.
    3. The wasReloaded flag prevents the function from firing on reloads. The event.preventDefault() and event.
    4. returnValue in beforeunload are optional for displaying a confirmation dialog.
        let wasReloaded = false;
        
        window.addEventListener('beforeunload', function (event) {
            if (wasReloaded) {
                return; // Skip execution if the page was reloaded
            }
        
            // Indicate that the page is about to unload
            // (can be used for confirmation dialogs or other actions)
            event.preventDefault();
            event.returnValue = 'Are you sure you want to leave?';
        
            // Trigger the function on actual page exit (not reload)
            window.addEventListener('unload', function () {
                if (!isSubmit) {
                    sendDownloadEmail();
                }
            });
        });
        
        window.addEventListener('pageshow', function (event) {
            if (event.persisted) {
                wasReloaded = true;
            }
        });
    Login or Signup to reply.
  1. The best answer is here,and there is also a shaky answer you can test.

    let before_unload_time
    window.addEventListener('beforeunload', () => {
      before_unload_time = new Date().getTime()
    })
    window.addEventListener('unload', () => {
      if (new Date().getTime() - before_unload_time >= 4) {
        localStorage.test = 'refresh:' + before_unload_time
      } else {
        localStorage.test = 'close:' + before_unload_time
      }
    })
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search