仅仅因为您看不到某个功能的用途并不意味着它没有用。
Stack Exchange 网络、GMail、Grooveshark、Yahoo!Mail 和 Hotmail 使用 onbeforeunload 提示来防止/警告用户在开始编辑内容后他们将离开页面。哦,是的,几乎每一个接受可保存用户输入数据的桌面程序都使用了这种在离开前提示用户的 UX 模式。
我有一个与此类似的函数:
window.onbeforeunload = function(){
// only prompt if the flag has been set...
if(promptBeforeLeaving === true){
return "Are you sure you want to leave this page?";
}
}
当用户尝试离开页面时,浏览器会为他们提供离开或留在页面上的选项。如果用户选择“离开此页面选项”,然后他们在页面完全卸载之前再次快速单击链接,则对话框再次触发。
这个问题有没有万无一失的解决方案?
注意:以下不是解决方案:
var alreadyPrompted = false;
window.onbeforeunload = function(){
// only prompt if the flag has been set...
if(promptBeforeLeaving === true && alreadyPrompted === false){
alreadyPrompted = true;
return "Are you sure you want to leave this page?";
}
}
因为用户可能会选择“留在页面上”选项,这会导致 futureonbeforeunload
停止工作。