Is there such a thing?
I know that I can hook my function on the click event of all links, but there are other situations where a page is changed, like refresh or wh
There's the beforeunload event, which is fired when the page is being torn down (either to follow a link, or if the window is being closed, or refresh, etc.). Example:
window.onbeforeunload = function(event) {
var s = "You have unsaved changes. Really leave?";
event = event || window.event;
if (event) {
// This is for IE
event.returnValue = s;
}
// This is for all other browsers
return s;
}
There are, for obvious reasons, very strict limits on what you can do in the handler of the beforeunload
event, and as you can see above beforeunload
handlers have a different signature than normal event handlers. Basically, your code can't do anything asynchronous, can't open new windows, and can't cancel the event. It can return a string, and if it does, the browser will pop up a window asking whether you really want to leave the page, and including your string in that pop-up.
From your comment on the question:
I need it before so I can fire a ajax request and update some things...
When the page is being torn down, you can usually get away with a synchronous ajax call (async: false
) provided it doesn't take too long. This is not a great idea and I would strongly recommend avoiding it if you can (for instance, with interim saves), as amongst other things it introduces a delay closing the page. But if you make the call synchronous (as opposed to the default, and greatly preferred, asynchronous call), usually the browser will let you do that. Of course, it does you no good if the browser abruptly terminates (crashes, is force-closed by the user, etc.).
Note that the async
flag is being deprecated and removed from jQuery (ticket). I think they plan to deprecate it in 1.8 and actually remove it in 1.9, but it's not hyper-clear from the blog post and ticket.