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:

<body onLoad="setAbandon();">

setAbandon assing the event handler to the onbeforeunload event:

function setAbandon() {
    window.onbeforeunload = function (e) {
        // Post to record the page unload
        post_to_url("/pageAbandon.php");
    };
}

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:

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

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.

 

References:

 Posted by at 3:54 pm

 Leave a Reply

(required)

(required)