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


i display message user if close asp.net web forms page or navigate away it. if click button, linkbutton, autopostback element, or else postback don't want show message.

so far have 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 seems stop autopostback events firing , still shows message linkbuttons etc.

how can this?

this take timestamp of when __dopostback called , carry out default behavior.

the onbeforeunload event show custom message when difference between it's timestamp , latest __dopostback timestamp greater allowedwaittime.

usage: include anywhere in page.

update:

this handle webform_dopostbackwithoptions also

(function ($) {      if (typeof $ !== 'function') {         throw new error('jquery required');     }      /* time in milliseconds allow between __dopostback call ,         showing onbeforeunload message. */     var allowedwaittime = 100,          timestamp = new date().gettime(),          // each function override         basefuncs = {             __dopostback: this.__dopostback,             webform_dopostbackwithoptions: this.webform_dopostbackwithoptions         };      // set timestamp when each basefunc called     (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 we'll set timestamp         manually on click. */     $('input[type="submit"]').click(function () {         timestamp = new date().gettime();     });      $(this).on('beforeunload', function (e) {          // return string if allowedwaittime has elapsed         if (e.timestamp - timestamp > allowedwaittime) {             return 'message';         }     }); }).call(window, jquery); 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -