Here is my solution for this stackoverflow question.

It is designed to return an onbeforeunload message when the user leaves the page (excluding postbacks). It does this by logging a timestamp each time a .NET control causes a postback (either full or partial using update panels). When this happens, if allowedWaitTime has elapsed, amessage will be returned.

Are there any best or better practices missing from this code and does anyone have an opinion on my style (albeit a small sample)?

(function ($) {

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

    /* The time in milliseconds to allow between a function 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);

    /* 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);

Interesting question,

I think the biggest thing is that callee is going the way of the Dodo bird.

JsHint does not like your code because you are using for( .. in .. ) without filtering properties, which is fine since you create the object with Object Notation, and I assume you did not modify the Object prototype. You are also creating functions/closures in a loop. Are you sure you need those closures there?

Other than well commented, and easy to follow, something that I would not mind using in one of my projects.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.