I want to know how I can capture the event where the user tries to close the page.
Example: When we write an email and we have not sent it and we try to close that window, then it sends you a message asking you to confirm that you are going to leave the page.
To display a confirmation message, the event is used
beforeunload
, the handler must return the confirmation string. In some browsers this is set in the event itself.According to MDN this is the most cross-browser way.
During this event, it is legal to make changes to the DOM since the page has not been loaded yet
alert
,confirm
orprompt
they have no effect in browsers that comply with the HTML5 specification.If you are only interested in executing an action when the page loads, you can use the event
unload
.With this event, the state of the page is as follows:
Note:
Note that attempting an ajax call on any of these events can have negative consequences if the response from the server is slow to be received. It is recommended to use a synchronous request, which blocks the download workflow. But this in turn has a significant impact on page download time and user experience.