JavaScript - 当用户确认离开页面时运行代码 [英] JavaScript - Run code when user confirms leaving page

查看:83
本文介绍了JavaScript - 当用户确认离开页面时运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户确认他要离开页面。我用jQuery这样做:

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?";
});

如果用户说是,我想运行一个函数来发出一个ajax请求来保存浏览器选项卡关闭之前的一些数据。这可能吗?在那种情况下如何?

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?

推荐答案

你所要求的是不可能的。 beforeunload 不允许您进行自己的提示,然后根据问题的答案进行分支。它只允许您运行代码或返回一个提示字符串,该字符串只是确定用户是否导航离开页面。

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.

在您的特定情况下,我建议您获得此回调时总是保存数据(如文字处理器中的自动保存)。如果用户选择留在页面上并进行更多更改,则可以在以后离开页面时再次保存新的数据状态。您必须仔细测试几个浏览器,以确保在 beforeunload 处理程序中启动的ajax调用将正确完成。它似乎应该如此,但浏览器之间可能存在实现差异。

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.

仅供参考,原因是 beforeunload 是如此严格,因为它必须防止恶意网页滥用,以防止您在需要时离开其网站。

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.

这篇关于JavaScript - 当用户确认离开页面时运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆