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
jQuery has unload function:
The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.
Note that this should be binded to window
object instead of document
:
$(window).unload(function() {
// do something
});
You can also bind handler to beforeunload
event:
$(window).bind('beforeunload', function() {
// do something, preferably ajax request etc
return 'are you sure?';
});
When a page is reloaded, whatever was there before will be gone. Thus, it seems like what you're talking about is something you'd do at DOMReady or "load" in the new page, since you can't "push" code from the former page into the new context.
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.