views:

49

answers:

1

I have a custom web part placed on one of the application page in SharePoint. This page it seems already have a function which gets executed on windows beforeunload javascript event.

My problem is that i too need to execute some client side code (to prompt user for any unsaved changes in my web part) on windows beforeunload event.

How can i achieve this ? I mean let the default event be fired as well as call my function also ?

Appreciate any help.

Nikhil.

+1  A: 

This should be possible by checking for an existing handler assigned to the onbeforeunload event and, if one exists, saving a reference to it before replacing with your own handler.

Your web part might emit the following script output to do this:

<script type="text/javascript">

// Check for existing handler
var fnOldBeforeUnload = null;
if (typeof(window.onbeforeunload) == "function") {
    fnOldBeforeUnload = window.onbeforeunload;
}

// Wire up new handler
window.onbeforeunload = myNewBeforeUnload;

// Handler
function myNewBeforeUnload() {
    // Perform some test to determine if you need to prompt user
    if (unsavedChanges == true) {
        if (window.confirm("You have unsaved changes. Click 'OK' to stay on this page.") == true) {
            return false;
        }
    }

    // Call the original onbeforeunload handler
    if (fnOldBeforeUnload != null) {
        fnOldBeforeUnload();
    }
}

</script>

This should allow you to inject your own logic into the page and make your own determination as to what code executes when the page unloads.

CBono