Why onbeforeunload event is not firing

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:

  1. Navigating to another page directly in the browser or via a link.
  2. Closing the current browser window or tab page.
  3. Reloading the current page.
  4. Manipulating the URL of the currently loaded page through the location object from JavaScript.
  5. Invoking the window.navigate method.
  6. Invoking the window.open or the document.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 !!!!')">

See here and here for more details.

Leave a Comment