Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display message if close window in ASP.NET but not on PostBack

I would like to display a message to the user only if they close my ASP.NET Web Forms page or navigate away from it. If they click any Button, LinkButton, AutoPostBack element, or anything else that will postback then I don't want to show the message.

So far I have the following code:

<script type="text/javascript">

var postback = false;

addToPostBack = function(func) {
    var old__doPostBack = __doPostBack;
    if (typeof __doPostBack != "function") {
        __doPostBack = func;
    } else {
        __doPostBack = function(t, a) {
            if (func(t, a)) old__doPostBack(t, a);
        }
    }
};

$(document).ready(function() {
    addToPostBack(function(t,a) {
        postback = true;
    });
});

$(window).bind("beforeunload", function() {
    if (!postback) {
        return "message";
    }
});
</script>

This works partially but seems to stop AutoPostBack events from firing and still shows the message for LinkButtons etc.

How can I do this?

like image 754
johna Avatar asked Oct 22 '22 02:10

johna


1 Answers

This will take a timestamp of when __doPostBack was called and then carry out the default behavior.

The onbeforeunload event will only show your custom message when the difference between it's timestamp and the latest __doPostBack timestamp is greater than allowedWaitTime.

Usage: include it anywhere in your page.

Update:

This will now handle WebForm_DoPostBackWithOptions also

(function ($) {

    if (typeof $ !== 'function') {
        throw new Error('jQuery required');
    }

    /* The time in milliseconds to allow between a __doPostBack call and 
       showing the onbeforeunload message. */
    var allowedWaitTime = 100,

        timeStamp = new Date().getTime(),

        // Each function to override
        baseFuncs = {
            __doPostBack: this.__doPostBack,
            WebForm_DoPostBackWithOptions: this.WebForm_DoPostBackWithOptions
        };

    // Set timeStamp when each baseFunc is called
    for (var baseFunc in baseFuncs) {
        (function (func) {
            this[func] = function () {
                var baseFunc = baseFuncs[func];
                timeStamp = new Date().getTime();
                if (typeof baseFunc === 'function') {
                    baseFunc.apply(arguments.callee, arguments);
                }
            }
        })(baseFunc);
    }

    /* Form submit buttons don't call __doPostBack so we'll set timeStamp 
       manually on click. */
    $('input[type="submit"]').click(function () {
        timeStamp = new Date().getTime();
    });

    $(this).on('beforeunload', function (e) {

        // Only return string if allowedWaitTime has elapsed
        if (e.timeStamp - timeStamp > allowedWaitTime) {
            return 'message';
        }
    });
}).call(window, jQuery);
like image 88
Zeb Rawnsley Avatar answered Oct 23 '22 19:10

Zeb Rawnsley