卸载警报错误“NS_ERROR_NOT_AVAILABLE”

2023-12-02

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

我正在使用这个简单的代码来测试 onunload 和 onbeforeunload 的一些内容。由于某种原因,每当我刷新/离开页面并导致 onunload 事件时,我在 Firebug 控制台中都没有收到警报和错误。如果我使用 onbeforeunload ,这可以工作并且不会出现错误,但我听说 onbeforeunload 不是很好的跨浏览器。

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

alert("test");

我并不是想警告测试变量,只是在有人试图指出这一点之前警告文本“测试”。


如果您希望它起作用,则必须将其放在 onbeforeunload 事件中,但 onbeforeunload 事件具有内置弹出窗口,而不是创建警报/确认弹出窗口。您所要做的就是返回一个字符串,当用户尝试离开页面时就会出现弹出窗口。如果没有返回变量,就不会弹出窗口。

  • 这样做的好处是弹出消息有 2 个按钮:“确定”和“取消”。
  • 如果用户点击“确定”,浏览器将继续离开该页面
  • 如果用户点击“取消”,浏览器将取消卸载并停留在当前页面
  • onbeforeunload事件是唯一可以取消onunload事件的弹窗

示例如下:

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

您似乎正在尝试在 onunload 事件中发出警报。这里的问题是为时已晚。该页面已经在卸载并且无法停止。您也许能够收到要显示的警报消息,但用户单击什么并不重要,因为页面已经在卸载。

最好的选择是使用 onbeforeunload 事件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

卸载警报错误“NS_ERROR_NOT_AVAILABLE” 的相关文章

随机推荐