How to detect when a user leaves a website with JavaScript?

Sometimes, we want to detect when a user leaves a website with JavaScript.

In this article, we’ll look at how to detect when a user leaves a website with JavaScript.

How to detect when a user leaves a website with JavaScript?

To detect when a user leaves a website with JavaScript, we can add an event listener for the unload event.

For instance, we write:

window.onunload = () => {
  console.log('unload')
};

to set window.onunload to a function that runs when the page is being unloaded.

Therefore, when we leave the page, we’ll see 'unload' logged.

Conclusion

To detect when a user leaves a website with JavaScript, we can add an event listener for the unload event.