Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *