Why onbeforeunload event is not firing

53,590

Solution 1

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.

Solution 2

Onbeforeunload is subject of one of bigest missunderstanding in the webdevelopers world :D

1) It refuses to call all blocking native functions (alert, prompt, confirm). It is obvious from User perspective.

2) it (according to MDN) should be registered by "addEventListener" (MDN)

3) It is fired only if there was ANY interaction of the user with the site. Without ANY interaction (even one click anywhere) event onbeforeunload won't be fired.

4) The aim of this event IS eg. secretly saving data left in forms (or else) on behalf of user (or logging user behavior etc.). It is NOT for blocking refreshing the site !

Thus there is no way (because it would be for nothing) to show personalised information.

The only sens is to hide the prompt window while reloading with prior saveing data.

5) If you want to hide the prompt window just NOT set any value for the event.returnValue field.

This example unload site (writing on console text "UNLOAD:1") without window prompt during refresh.

window.addEventListener("beforeunload", function(event) {
  console.log("UNLOAD:1");
  //event.preventDefault();
  //event.returnValue = null; //"Any text"; //true; //false;
  //return null; //"Any text"; //true; //false;
});

This example unload site (writing on console text "UNLOAD:1") WITH window prompt during refresh.

window.addEventListener("beforeunload", function(event) {
  console.log("UNLOAD:1");
  //event.preventDefault();
  event.returnValue = null; //"Any text"; //true; //false;
  //return null; //"Any text"; //true; //false;
});

You can use any kind of value to event.returnValue (as listed on the right). It is just coding style matter.

Both event.preventDefault nor return has no influence on this event (so in your code you can omit those commented lines).

Tested on Chrome, Edge, Firefox, Opera (verified on 23.09.2019). Hope it helps.

[EDIT:]

To avoid reloading mobile application by accidentally swipe/drag of the screen (eg. google maps, images and any other stable content) this css trick can be usefull:


    body {
       overscroll-behavior-y: contain !important;
    }

The application will be safe against reloading.

It is woth to consider to give to user another possibilty (eg. some button) to reload if needed.

Solution 3

I faced problem where neither beforeunload nor onunload worked to execute one ajax call that should get called when user closes the browser. In fact, none of the methods worked. The javascript method was inside the body tag, which was actually the problem. It was magically solved when I moved the javascript method inside Head tag.

Share:
53,590
Hesham
Author by

Hesham

Management &amp; Software Technology Advisor - MBA, CIFE™ (Odoo / Python) &amp; Independent Executive Consultant

Updated on July 29, 2022

Comments

  • Hesham
    Hesham almost 2 years

    I tried the code on Chrome, FireFox and Safari. Still the onbeforeunload does not fire. I also tried the onunload, but it did not work.

    Here is the code I am experimenting with:

    <!doctype html>
    <html lang="en">
    <head>
      <title> Output to a Page </title>
      <meta charset="utf-8">
      <script> 
        window.onload = init;
        window.onclick = clk;
        window.onbeforeunload = closing;
        function clk() {
            window.alert("Ouch !!");
        }
        function closing() {
            console.log("function alrt WORKS !!!!");
            window.alert("closing now.....");
        }
        function init() {  
          var output = "";
          for (var mms = 5; mms > 0; mms--) {
            if (mms >= 3) {
                output += "Still lots of M&amp;Ms left, so eat more!<br>";
            } else {
                output += "Getting low on M&amp;Ms, take it easy!<br>";
            }
          }
          output += "All out of M&amp;Ms";
          var e = document.getElementById("output");
          e.innerHTML = output;
        }
    
      </script>
    </head>
    <body>  
      <p id="output"></p>
    </body>
    </html>
    
  • user3351605
    user3351605 over 8 years
    Currently this is the only way I have been able to achieve full cross-browser support for the onbeforeunload event (Firefox does not fire it under certain conditions). Thanks for this great answer!
  • Josh Powlison
    Josh Powlison about 6 years
    Could you share a code example? I'm not quite sure what you mean.
  • user1039663
    user1039663 over 4 years
    For me the most valuable info is that weird third point. Thx!!
  • Kai Lehmann
    Kai Lehmann over 3 years
    3) was a very valuable information. I wondered why I tried thousands of things and it never fired. Thanks
  • Hiro
    Hiro almost 3 years
    @user1039663 It's similar with the audio playing rule that got placed recently(?). User has to "interact" with the page in order for the page to output sound of media.