2016-09-21 51 views
1

我有一个测试页,用户可以在指定的时间内回答它。如何在条件成立时禁用onbeforeunload?

对于时间限制,我使用了一个javascript倒数计时器。直到时间未完成,用户必须无法关闭窗口。

对于我用onbeforeunload窗口事件要防止窗口关闭这样的:

<script language="JavaScript"> 
    window.onbeforeunload = confirmExit; 
    function confirmExit() { 
     return "You have attempted to leave this page. Are you sure?"; 
    } 
</script> 

在另一方面,在倒数计时器,我设置一个timeUp函数重定向用户完成时间后导致页面。

在这种情况下,因为在onbeforeunload以上发射,重定向失败,并且上面的消息显示给用户。

有什么办法当条件成立时,可以禁用onbeforeunload事件?

回答

1

如果onbeforeunload函数不会返回任何东西 - 浏览器不会显示任何消息。

既然你说过你使用了定时器功能来检查你是否应该显示用户的消息。

var displayMessage = true; 
setTimeout(function() { 
    displayMessage = false; 
}, 10000); 

function confirmExit() { 
    if (displayMessage) { 
     return "You have attempted to leave this page. Are you sure?"; 
    } 
} 
window.onbeforeunload = confirmExit; 

在上面的代码 - 10秒后displayMessage的值将是假的,并且如果用户将尝试在10秒后刷新/退出页面浏览器将不显示该消息。

1

呼叫解除绑定使用beforeunload事件处理程序:

$(window).unbind('beforeunload'); 

或者试试

window.onbeforeunload = null;` 
相关问题