-1

Question:

I am using ASP.NET web forms, c#.

I need to execute a JS function just before the page closes - any which way it closes - being a redirect or any other method.

Extra Info:

As some extra info; the function will be an HTTP POST to a different page, I need some server side code to execute.

With this info in mind - a solution allowing me to execute server-side code when a page closes will work for me as well.

Community
  • 1
  • 1
Terrance00
  • 1,658
  • 1
  • 20
  • 29
  • No can do, not possible. That feature was far too abused by people in the past. There *is* a onpageunload event, but there is nothing to ensure that your ajax won't time out first -- and in fact it's likely. Also no way to handle a "page close" network connection is lost, power goes away, etc. – Jeremy J Starcher May 29 '15 at 08:16
  • Since this is a client side feature, you wouldn't need a solution that relates to ASP.NET, but only JavaScript – ericosg May 29 '15 at 08:17
  • I thought it might be impossible. Going to have think of some other solution to my problem. Thanks. – Terrance00 May 29 '15 at 08:22

1 Answers1

1

Have a look at the JavaScript function window.onbeforeunload.

Essentially, browsers fire this event when they detect that the page is closing, and allow you to customize a message by returning a string from this function.

You cannot however, control if the user wants to force close the page early, or unexpectedly.

window.onbeforeunload = function(e) {
    // do some ajax post here
    // 

    // Display a message (or generic message in some browsers) and allow the user to cancel leaving the page.
    return 'Dialog text here.';
};

Note that this solution tries to warn the user and allows the unload to be cancelled. This might not be ideal for you, but should work.

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

ericosg
  • 4,926
  • 4
  • 37
  • 59