OnUnload Alert Error "NS_ERROR_NOT_AVAILABLE"

5
<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.

javascript
alert
onunload
window.onunload
asked on Stack Overflow May 13, 2013 by Cains • edited May 13, 2013 by Michal Borek

1 Answer

13

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.

  • The great thing with this is that the pop-up message has 2 buttons: OK and Cancel.
  • If the user hits OK, the browser will continue to navigate away from the page
  • If the user hits Cancel, the browser will cancel the unload and will stay on the current page
  • The onbeforeunload event is the only pop-up that can cancel the onunload event

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.

answered on Stack Overflow Jun 4, 2013 by Brian

User contributions licensed under CC BY-SA 3.0