JavaScript beforeunload Event. How to capture browser or window close event?

One of a very useful JavaScript events is the beforeuload event. This event will execute the JavaScript codes or functions that are bound to the event right before the page or document is about to be unloaded. Review the example before on how I used the beforeunload event and leave a comment to let me know if you have any question about this event.

//Bind the event to the page
window.addEventListener("beforeunload", function(e) {
    if (inFormOrLink == false) //Only execute the code when leaving the page
       //Example 1: Display a message 
       alert('You are leaving the page');

       //Example 2: Call your function

function YourCustomFunction()
      //Your logic here.

Please subscribe for more useful coding examples.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s