2013-05-13 28 views
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> 

我正在使用这个简单的代码来测试onunload和onbeforeunload的一些事情。出于某种原因,无论何时刷新/离开页面并导致onunload事件,我都没有在Firebug控制台发出警报和错误。如果我使用onbeforeunload这个工程,我得到没有错误,但我听说onbeforeunload是不是很好的跨浏览器。OnUnload Alert Error“NS_ERROR_NOT_AVAILABLE”

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

alert("test"); 

我没有试图提醒测试变量,只是文本“测试”之前任何人试图指出。

+0

你在IE中试过这个东西...? – Pandian 2013-05-13 08:06:49

+1

[“showModalDialog()','alert()','confirm()'和'prompt()'方法现在允许在页面隐藏期间,在卸载和卸载事件之前不做任何事情。”](http:// www .w3.org/TR/html5-diff /#changes-2011-05-25) – 2013-05-13 08:25:32

+0

@Pandian显然是一个Firefox错误(提示:看看'NS_'和'nsI'前缀以及Firebug的提及)。 – 2013-05-13 08:27:12

回答

13

如果要使用它,它必须位于onbeforeunload事件中,而不是创建警报/确认弹出窗口,onbeforeunload事件具有内置弹出窗口。你所要做的就是返回一个字符串,当用户试图离开页面时,弹出窗口会出现。如果没有返回变量,则不会弹出。

  • 伟大的事情是,弹出消息有2个按钮:确定和取消。
  • 如果用户点击OK,浏览器将继续从页面
  • 导航路程,如果用户点击取消,浏览器将取消卸载并会留在当前页面
  • 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事件一起去。