我想在用户尝试关闭窗口或选项卡时显示警报消息。如何实现呢?我已经尝试了下面的代码,但无法解决问题
<!DOCTYPE html>
<html>
<body>
<p>This example uses the addEventListener() method to attach a "beforeunload" event to the window object.</p>
<p>Close this window, press F5 or click on the link below to invoke the beforeunload event.</p>
<script>
var unloadEvent = function (e) {
var confirmationMessage = "Warning: Leaving this page will result in any unsaved data being lost. Are you sure you wish to continue?";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome etc.
};
window.addEventListener("beforeunload", unloadEvent);
</script>
</body>
</html>