The onbeforeunload
event is not cancel-able, because of security reasons, but if an event handler function for the onbeforeunload
event returns a string value, this text will be shown in a confirmation dialog box, where the user can confirm whether he wants to stay or leave the current page.
Note that event listeners cannot be registered for the onbeforeunload
event with the addEventListener
and attachEvent
methods (only Safari and Google Chrome support it). For a cross-browser solution, register the event handler in HTML (with the onbeforeunload
attribute of the body
element) or with the onbeforeunload
in-line event property of the window
object. See the examples below for details.
Examples:
In HTML:
<ELEMENT onbeforeunload="handler">
In JavaScript:
object.onbeforeunload = handler; object.addEventListener ("beforeunload", handler, useCapture);
Actions that invoke the onbeforeunload
event:
- Navigating to another page directly in the browser or via a link.
- Closing the current browser window or tab page.
- Reloading the current page.
- Manipulating the URL of the currently loaded page through the location object from JavaScript.
- Invoking the
window.navigate
method. - Invoking the
window.open
or thedocument.open
method to open a document in the same window.
Try to modify your code, like this:
window.onbeforeunload = closing; /* other code here */ var closing = function () { console.log("function alrt WORKS !!!!"); window.alert("closing now....."); }
…or just put directly the code in your body
tag:
<body onbeforeunload="alert('function alrt WORKS !!!!')">