简体   繁体   English

JavaScript-用户确认离开页面后运行代码

[英]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: 我用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. 如果用户说“是”,那么我想运行一个函数,该函数在关闭浏览器选项卡之前发出ajax请求以保存一些数据。 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. beforeunload不允许您自己进行提示,然后根据问题的答案进行分支。 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. 您将必须仔细测试几个浏览器,以确保在beforeunload处理程序中启动的ajax调用将正确完成。 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. 仅供参考, beforeunload之所以如此严格,是因为它必须防止恶意网页滥用,以防止您在需要时离开其网站。

As jfriend00 mentioned what you are trying to do it not possible. 正如jfriend00提到的那样,您尝试执行的操作是不可能的。 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. 希望这样做是为了给您的ajax调用发送时间,并将新数据通知服务器。 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. 请记住,当用户强行关闭浏览器时,不会触发此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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