简体   繁体   中英

JavaScript - Run code when user confirms leaving page

I want the user to confirm that he wants to leave the page. I do that this way with jQuery:

$(window).bind('beforeunload', function(){ 
    return "Are you sure?";
});

If the user says "yes", I want to run a function that makes an ajax request to save some data, before the browser tab closes. Is this possible? And how, in that case?

What you are asking is not possible. beforeunload does not allow you to do your own prompting and then branch based on how the question is answered. It only lets you run code or return a prompt string that simply determines whether the user navigates away from the page or not.

In your particular case, I would suggest that you always save the data when you get this callback (like an autosave in a word processor). If the user elects to stay on the page and make more changes, you can then save the new state of the data again at a later time when they leave the page. You will have to carefully test several browsers to make sure that an ajax call that is started in a beforeunload handler will properly complete. It seems like it should, but there could be implementation differences between browsers.


FYI, the reason beforeunload is so strict is because it has to prevent abuse by malicious web pages that prevent you from leaving their web site when you want to.

As jfriend00 mentioned what you are trying to do it not possible. You're best bet though is to be pessimistic when they press the back button. By this I mean:

$(window).bind('beforeunload', function(){ 
    $.ajax({
        //Do ajax call to save
    });
    return "Are you sure?";
});

What this will do is hopefully give time for your ajax call to be sent and notify the server of the new data. I say hopefully because the browser will kill all requests when you navigate away from the page.

Another thing to keep in mind this will not be triggered when a user forcibly closes the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM