Prabath Udayanga
Prabath Udayanga

Reputation: 1

How to detect when user leaves the web page or not?

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();
        }
    });
}

Upvotes: -1

Views: 585

Answers (1)

moon
moon

Reputation: 1132

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
  }
})

Upvotes: -1

Related Questions