window.onbeforeunload处理ok并取消选项 [英] window.onbeforeunload handling ok and cancel options
问题描述
我有一个window.onbeforeunload函数,它会生成默认消息你确定要离开此页面......。
如果我们点击确定,我们会被重定向到新的链接,如果我们按取消,我们会被重定向回同一页面。
I have a window.onbeforeunload function which generates the default message "Are you sure you want to navigate away from this page...." . If we click on "OK" we are redirected to a new link and if we press "cancel" we are redirected back to the same page.
I当我们按确定并离开页面时,想要从页面保存一些数据。我们如何知道是否按下确定或取消,然后进行事件调用并继续使用确定/取消选项。
I want to save some data from the page when we press "ok" and move away from the page. How can we know if "ok" or "cancel" has been pressed , then make an event call and continue with the "ok"/"cancel" option.
推荐答案
一种可能的方法可能是挂钩 onunload
事件,如果调用该处理程序,你知道用户选择确定
。
A possible approach might be to hook into the onunload
event as well, and if that handler is called, you know that the user chose OK
.
在 onbeforeunload
中,设置一个超时回调在一段时间后调用(例如1秒),如果调用它,则用户可能已选择取消
。
In onbeforeunload
, set a timeout callback that is called some time afterwards (e.g. 1 second), and if it is called, the user might have selected Cancel
.
不确定这对于竞争条件有多安全。
Not sure how safe this is regarding race conditions though.
这篇关于window.onbeforeunload处理ok并取消选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!