javascriptalertonunloadwindow.onunload

OnUnload Alert Error "NS_ERROR_NOT_AVAILABLE"


<html>
<body>

<button type="button" onclick="clickme()">Click Me</button>

<script>
var test = 0;

function clickme() {
  test = 1;
  console.log(test);
}

window.onunload = function() {
  alert("test");
}
</script>

</body>
</html>

I'm using this simple code to test some things with onunload and onbeforeunload. For some reason whenever I refresh/leave the page and cause the onunload event I get no alert and an error in the Firebug console. If I use onbeforeunload this works and I get no error, but I hear onbeforeunload isn't very good cross-browser.

NS_ERROR_NOT_AVAILABLE: Component returned failure code: 0x80040111     
(NS_ERROR_NOT_AVAILABLE) [nsIDOMWindow.alert]

alert("test");

I am not trying to alert the test variable, just the text "test" before anyone tries to point that out.


Solution

  • If you want that to work, it will have to be in the onbeforeunload event, but instead of creating an alert/confirm pop-up, the onbeforeunload event has a built in pop-up. All you have to do is return a string and the pop-up will appear when the user tries to navigate away from the page. If there is no return variable, there will be no pop-up.

    An example is below:

    <script type="text/javascript">
    
    window.onbeforeunload=before;
    window.onunload=after;
    
    function before(evt)
    {
       return "This will appear in the dialog box along with some other default text";
       //If the return statement was not here, other code could be executed silently (with no pop-up)
    }
    
    function after(evt)
    {
       //This event fires too fast for the application to execute before the browser unloads
    }
    
    </script>
    

    It seems like you are trying to do an alert in the onunload event. The issue here is that it's too late. The page is already unloading and there is no stopping it. You may be able to get an alert message to show, but it doesn't matter what the user clicks because the page is already unloading.

    Your best bet is to go with the onbeforeunload event.