Fallenreaper
Fallenreaper

Reputation: 10704

Is there a way to write some javascript functionality when users try to leave the page?

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.

Upvotes: 0

Views: 144

Answers (3)

Magicmarkker
Magicmarkker

Reputation: 1063

jQuery(window).on(
    "beforeunload", 
    function() { 
        return confirm("Do you really want to close?") 
    }
)

Upvotes: 3

Marcelo Biffara
Marcelo Biffara

Reputation: 831

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

$(window).unload(function() {
  alert('Handler for .unload() called.');
});

Upvotes: 6

Kevin Boucher
Kevin Boucher

Reputation: 16675

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.

Upvotes: 3

Related Questions