控制window.onbeforeunload事件

时间:2012-08-24 05:59:52

标签: javascript jquery

出于好奇,我可以控制window.onbeforeunload事件,如检查用户是否决定离开页面或留在其中,我可以根据他的决定提出警告或某些功能,如果有,请告诉我

<script type="text/javascript">
$(window).bind("beforeunload",function(){
if(//stay on page)
alert("i want to stay on the page");
else //leave page
 alert("i want to leave the page");
});
</script>

我理解window.onbeforeunload是一个事件,它会给用户一个消息,告诉他你可能忘记在离开之前做某事但这个任务只是出于好奇而感谢你

3 个答案:

答案 0 :(得分:1)

您只能返回一个字符串,该字符串将显示一个对话框确认信息,显示您返回的字符串(但需要额外的确定/取消按钮来确认操作)。

<script type="text/javascript">
$(window).bind("beforeunload",function(){
return 'Are you sure you want to leave this page?';
});
</script>

答案 1 :(得分:0)

您无法获得onbeforeunload的结果。此外,即使您以某种方式设法找到获得结果的方法,您也无法提出警报。你可以运行另一个功能。

  

The showModalDialog(), alert(), confirm() and prompt() methods are now allowed to do nothing during pagehide, beforeunload and unload events.

答案 2 :(得分:0)

放一秒钟的计时器。在卸载时清除它。应该工作,但没有测试。

window.addEventListener('beforeunload', function (event) {

  var timeId = setTimeout(yourFunctionIfTheUserStays, 1000);

  window.addEventListener('unload', function (event) {
    clearTimeout(timeId);
  })
  return 'Are you sure you want to leave this page?';
});