0

I was trying to figure out if there is a way to execute scripts if a user tries to navigate away from your website.

Im not thinking malicious like when you get asked a million times if you want the leave the site, but more-so doing an ajax request to save data.

If Possible to do it when they attempt to navigate away, maybe there is also a way to do it when they click the back-button as well?

If there is something in place currently that would be useful.. It would be great for the last attempt to save data on the page while they are navigating elsewhere.

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129
  • 2
    `onbeforeunload` and `onunload` depending on what needs to be executed and whether the browser honors the event. – zzzzBov Dec 07 '12 at 20:24
  • 3
    Related: http://stackoverflow.com/questions/1821625/ajax-request-with-jquery-on-page-unload (not a duplicate -- just someone facing an `unload`+Ajax problem you might face later) – apsillers Dec 07 '12 at 20:29
  • THANKS! THat is some useful information – Fallenreaper Dec 07 '12 at 20:36

3 Answers3

6

the unload event is for that http://api.jquery.com/unload/

$(window).unload(function() {
  alert('Handler for .unload() called.');
});
Marcelo Biffara
  • 811
  • 4
  • 8
3

You want window.onbeforeunload: https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload or window.onunload: https://developer.mozilla.org/en-US/docs/DOM/window.onunload

Working with these can be a little tricky but they're your only (reasonable) option.

Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
3
jQuery(window).on(
    "beforeunload", 
    function() { 
        return confirm("Do you really want to close?") 
    }
)
Magicmarkker
  • 1,063
  • 7
  • 25