Categories
JavaScript Answers

How to run JavaScript code on window close or page refresh?

Spread the love

Sometimes, we want to run JavaScript code on window close or page refresh.

In this article, we’ll look at how to run JavaScript code on window close or page refresh.

How to run JavaScript code on window close or page refresh?

To run JavaScript code on window close or page refresh, we add an event handler for the beforeunload event.

For instance, we write

window.onbeforeunload = () => {
  // Do something
};

to set the window.onbeforeunload property to a function that runs when the window closes or the page refreshes.

Conclusion

To run JavaScript code on window close or page refresh, we add an event handler for the beforeunload 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.