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

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.