一个含有表单的页面,用户可能会意外点击链接而导致离开此页面,这时有可能导致表单中填写的数据丢失。
下面的代码用于在用户离开当前页面时进行提示。如果是表单的提交动作,则不进行提示。
(function(){
var unload_check = true;
$("form").submit(function(){
unload_check = false;
});
window.addEventListener('beforeunload', function(evt){
unload_check = true; // for the case submit does cause unload
if(!unload_check) return;
var message = 'You are on form editing page.\nLeave before submit may cause your data lost!';
(evt || window.event).returnValue = message; // Important for cross browser
return message;
});
})();