Jul 012013
Article Javascript

Sometimes, some type of processing is required when a user decides to leave one of the pages of our web site.

For instance, the page might include a form where the user has entered some data. In this case, it is desirable to warn the user with a request to save, or to explicitly discard the changes.

This post explains how to capture and process in javascript the page abandon event that is triggered when the user is about to leave a page.

To do this, we add to the “onload” handler of the page a function “setAbandon” that assigns an event handler to the “onbeforeunload” event.

In the HTML code, this is done in the <body> tag as:

setAbandon assing the event handler to the onbeforeunload event:

As can be seen, in the sample code above, the event handler just calls the  “post_to_url” function. This function issues a POST request to “/pageAbandon.php”. We could check previously any condition (form changed, time elapsed,…), present a warning popup, or perform any other action desired.

In our example, the post_url function can be implemented as shown below:

This implementation allows sending some parameters with the request.

In the same way, we can implement extra functionality in the “pageAbandon.php” script. For instance, we can store in a database the received parameters, etc.



 Posted by at 3:54 pm

 Leave a Reply