用户确认“离开页面”时触发javascript功能 [英] Fire javascript function when user confirms 'Leave Page'
问题描述
当用户试图离开页面时,我正在使用以下代码触发 confirmExit()
函数:
I am using the code below to fire a confirmExit()
function when the user tries to leave the page:
window.onbeforeunload = confirmExit;
function confirmExit(){
return "Are you sure you want to exit this page?";
}
此外:
该页面还会触发AJAX函数以动态更新数据库。因此,当用户离开页面时,我需要删除所有即时数据。
The page also fires AJAX functions to update a database 'on the fly'. As a result, when the user leaves the page, I need to delete all that 'on the fly' data.
是否可以在用户调用javascript函数时点击离开页面按钮?
Is it possible to call a javascript function when the user clicks the 'Leave Page' button?
推荐答案
您可以尝试使用 window.onunload
:
You can try to use window.onunload
:
window.onbeforeunload = function () {
return "Are you sure?";
}
window.onunload = function () {
console.log("Too bad. Goodbye.");
}
window.onunload
只有当用户点击离开此页面按钮时才会触发。
window.onunload
will be fired only when user clicks "Leave this page" button.
如果您想在用户点击取消时执行某些操作,您可以尝试以下方法:
If you want to do something if user clicks "Cancel" you can try the following approach:
window.onbeforeunload = function () {
setTimeout(function () {
setTimeout(function () {
console.log("Great decision!");
}, 200);
}, 1);
return "Are you sure?";
}
第一个 setTimeout
将您的代码放入事件队列。它将在确认框关闭后立即触发。如果页面未过早关闭,则会在一段时间后触发第二个 setTimeout
。
对于那些正在做某事的人XHR onunload
:确保在页面关闭之前使用同步方法完成请求。例如。在 jQuery.ajax
或 XMLHttpRequest.open中使用
in plain js。 async:false
(method,url,false )
For those who are doing some XHR onunload
: make sure to use synchronous approach to complete your requests before the page is closed. E.g. use async: false
in jQuery.ajax
or XMLHttpRequest.open(method, url, false)
in plain js.
这篇关于用户确认“离开页面”时触发javascript功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!