I want to show an alert message when a user tries to close the window or tab. How to achieve this? I have tried the code below but I am unable to solve the problem
<!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>