Javascript – Can Response.Redirect and OnBeforeUnload play nice together

Does anyone know how to detect in a OnBeforeUnload event that the server side code sent a Response.Redirect? I want to prompt a user to keep them from moving away from a page before it's time, but when the server redirects I it shouldn't prompt the user.

I'm working with legacy code that extensively uses Response.Redirect and I'm not interested in changing the way the redirect occurs. Please don't suggest I use X redirect method.

It should be possible to do this based on the response code in the XMLHttpRequest object as a response redirect should send back a 302.

Edit: The Response.Redirect sends back a 200, with a redirect code in the body which then does a window.location.href = new page in the ASP.Net code. Is there any way to get to the server response to determine that this has happened?

Best Solution

I worked out a solution to it.

When the PageRequestManager is processing the response from the server, it will set the _processingRequest flag. In order to allow response.redirect to pass through, I changed my javascript to check for that. The event now looks like this:

window.onbeforeunload = function() {
  var prm = Sys.WebForms.PageRequestManager.getInstance();
  if (!prm._processingRequest){ 
    return "Are you sure you want to leave?";