AJAX Page - Knowledge Base

« Back to Knowledge Base list

Setting onbeforeunload method

Q:

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

A:

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

// add beforeunload event
function addBeforeunloadEvent(func) {

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


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

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

function myBeforeunload()
{
        // user defined codes to be executed on page beforeunload
}

Add this script at the end of yor page:

... </html>

<script language="JavaScript" type="text/javascript">
        window.onload = function(){addBeforeunloadEvent(myBeforeunload)};
</script>