AJAX Page - Knowledge Base

« Back to Knowledge Base list

Setting onunload method

Q:

How to set user defined code to execute on page unload in an AJAXPage?

A:

To execute user defined code on page unload, the following JS code needs to be added in the page:

// add unload event
function addUnloadEvent(func) {

     var oldunload = window.onunload;
     if (typeof window.onunload != 'function') {
            window.onunload = func;
     }
     else {
            window.onunload = function() {
                    if (oldunload) {
                            oldunload();
                    }
                    func();
            }
     }
}


The addUnloadEvent method should be called with the function that needs to be executed on page unload as the parameter.

For example, if myUnload method is needed to be executed on page unload, the definition will be as follows:

function myUnload()
{
        // user defined codes to be executed on page unload
}

addUnloadEvent(myUnload);