OnUnload Alert Error “NS_ERROR_NOT_AVAILABLE”

无人久伴 提交于 2019-12-19 19:55:09

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/16517284/onunload-alert-error-ns-error-not-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!