Javascript event that runs before page changes

Is there such a thing?

I know that I can bind my function to the click event of all links, but there are other situations when the page changes, for example, refreshes or when another script changes window.location


In the end, I did this by sending the postMessage line from the unload event, for example:

$(window).bind('unload', function(e){
  window.parent.postMessage('unloading');
});

in parent document:

$(window).bind('message', function(e){     
  if(e.originalEvent.data == 'unloading'){
    // ajax stuff here
  }
});

It seems to work. I probably should have mentioned that iframe is involved there :)

+5
source share
3 answers

Here is the beforeunloadevent that fires when the page breaks (either follow the link, or if the window closes, or update, 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;
}

, beforeunload, , , beforeunload , . , , . , , , .

:

, ajax- ...

, ajax (async: false) , . , , (, ), . ( ), . , , (, ..).

, async jQuery (ticket), , 1.8 1.9, - .

+16

jQuery unload :

, . . , , URL- . . . .

, window document:

$(window).unload(function() {
    // do something
});

beforeunload:

$(window).bind('beforeunload', function() {
    // do something, preferably ajax request etc
    return 'are you sure?';
});
+4

When the page reloads, everything that was before that will disappear. So it looks like you are talking about what you are doing in DOMReady or “loading” on a new page, since you cannot “push” the code from the previous page into the new context.

+1
source

All Articles