以下是一个示例代码,用于在用户尝试离开页面时显示一个提示消息:
window.addEventListener('beforeunload', function (e) {
// 取消事件的默认行为
e.preventDefault();
// Chrome需要返回一个空字符串来触发提示消息
e.returnValue = '';
// 显示提示消息
var confirmationMessage = '确定要离开吗?';
(e || window.event).returnValue = confirmationMessage; // 兼容旧版IE
return confirmationMessage;
});
这段代码使用beforeunload
事件,在用户尝试离开页面之前触发。在事件处理程序中,我们取消了事件的默认行为,并将returnValue
属性设置为空字符串来触发提示消息。然后,我们可以通过设置confirmationMessage
变量来定义自定义的提示消息。
请注意,浏览器可能对beforeunload
事件的滥用进行限制,以防止滥用行为。因此,显示提示消息并不能完全阻止用户离开页面。它只是一个提醒,用户可以选择忽略并离开页面。