2016-08-16 50 views
1

我需要你的帮助窗口前完成,等待功能,关闭使用window.onbeforeunload

看来,当我关闭窗口(IE 11),确认框弹出,我点击确定按钮,函数想运行,但在函数有机会完成之前窗口关闭(将记录保存到数据库)。代码如何修改,使得函数imts_save_changes()有机会在关闭窗口之前完成其数据库操作?

下面是标记:

<!DOCTYPE html> 

<html> 

<head> 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 

<style type="text/css"> 

</style> 

<script type="text/javascript"> 

window.onbeforeunload = function() { return test() } 

function test() { 

    if (confirm("would you like to run the last function before closing the window?")) { 

     imts_save_changes() 

     alert("record saved") 

    } 
} 

</script> 

</head> 

<body></body> 

</html> 

有问题的代码:

window.onbeforeunload = function() { return test() } 

function test() { 

    if (confirm("would you like to run the last function before closing the window?")) { 

     imts_save_changes() 

     alert("record saved") 

    } 
} 
+0

您需要取消导航,并使用onbeforeunload及其正常消息。 – epascarello

+0

Javascript无法阻止关闭窗口。这是一项安全功能,用于在用户允许其破坏之前保持窗口打开的恶意软件。 – Barmar

+0

@barmar HTA不关心安全性... – Teemu

回答

2

当你confirm封闭由onbeforeunload事件发射窗口,它立即关闭;你不能取消后续动作(真正关闭)。你所能做的就是警告用户,在这种情况下,关于未保存的更改,并给他机会不确认行动。

我不是100%确定,但我认为alertconfirm函数会冻结DOM,因此在用户交互之前不会发生任何事情。

IMO,你应该改变你的应用程序的设计。