提示信息需要再页面中显示地添加beforeunload事件处理,否则不会在离开页面时进行提示,这个方法不仅仅可以用在表单页面,也可以用在非表单页面。
在现代浏览器中,提示信息通常是一个标准的提示,自定义的文本可能不会被显示,但仍需返回自定义文本
处理思路
- 事件监听器:beforeunload 事件监听器必须显式添加到 window 对象上,浏览器在用户尝试关闭、刷新或导航离开页面时才会触发这个事件。
- 标记表单已修改:通过监听表单的 input 事件,当用户对表单进行修改时,将 formIsDirty 设置为 true。
- 保存按钮:假设保存操作完成后,设置 formIsDirty 为 false,表示表单数据已经保存。
- 提示用户:在 beforeunload 事件中检查 formIsDirty 是否为 true。如果为 true,则返回一个消息,触发浏览器的离开页面确认对话框。
代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Save Warning</title>
</head>
<body>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<br>
<button type="button" onclick="saveForm()">Save</button>
</form>
<script>
let formIsDirty = false;
// 监听表单输入事件
document.getElementById('myForm').addEventListener('input', function() {
formIsDirty = true;
});
// 保存表单数据
function saveForm() {
// 假设保存操作在这里执行
formIsDirty = false;
alert('Form saved!');
}
// 在用户尝试离开页面时提示
window.addEventListener('beforeunload', function (e) {
if (formIsDirty) {
const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
(e || window.event).returnValue = confirmationMessage; // 兼容旧版本浏览器
return confirmationMessage; // 现代浏览器
}
});
</script>
</body>
</html>