Wednesday, February 6, 2008

Using Ajax Behavior to capture Before Unload event

In my previous post
http://jqdjha.blogspot.com/2008/02/handling-onbeforeunload-event-double.html
I discussed how to use setTimeout to avoid double firing onbeforeunload event in IE6 and IE7.
If the web page support ASP.Net Ajax Library, then we can use Ajax behavior to inject our code from that previous post to window, body, frameset tag, all of which support beforeunload event in IE. Note that we can control whether to attach "NavAway Behavior" or not:

<script>
      $create(JQD.NavAwayWarning,null,null,null,window);
</script>


var globalIsThe2ndNavAway=false;
Type.registerNamespace("JQD");


JQD.NavAwayWarning= function (element) {
      JQD.NavAwayWarning.initializeBase(this,[element]);
      this._navAwayHandler = Function.createDelegate(this,this._onNavAway);
}


JQD.NavAwayWarning.prototype = {

_onNavAway : function (e) {

      if (globalIsThe2ndNavAway) return;
      window.event.returnValue="You are losing changes."
      globalIsThe2ndNavAway=true;
      setTimeout("globalIsThe2ndNavAway=false;",0) ;

},

initialize: function () {
      JQD.NavAwayWarning.callBaseMethod(this,'initialize');
      $addHandler(this.get_element(),'beforeunload',this._navAwayHandler);
},

dispose: function() {
      JQD.NavAwayWarning.callBaseMethod(this,'dispose');
      $removeHandler(this.get_element(),'beforeunload',this._navAwayHandler);
}

}
JQD.NavAwayWarning.registerClass('JQD.NavAwayWarning', Sys.UI.Behavior);

No comments: