拦截页面退出事件

Chr*_*nce 115 javascript internet-explorer javascript-events

在我的系统中编辑页面时,用户可能决定导航到另一个网站,这样做可能会丢失他们未保存的所有编辑内容.

我想拦截任何转到另一个页面的尝试,并提示用户确保他们希望这样做,因为他们可能会丢失他们当前的工作.

Gmail以非常类似的方式执行此操作.例如,撰写新电子邮件,开始在邮件正文中键入内容并在地址栏中输入新位置(比如twitter.com或其他内容).它会提示"你确定吗?"

想法如何复制这个?我的目标是IE8,但也希望与FF和Chrome兼容.

Eli*_*rey 147

与Ghommey的答案类似,但这也支持旧版本的IE和Firefox.

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};
Run Code Online (Sandbox Code Playgroud)

  • @mtmurdock这只是Javascript语法来声明多个变量.`var foo,bar;`与`var foo;``var bar;`相同 (7认同)
  • @mtmurdock,第二个语句"_var_ e = e || window.event;" 意味着设置**e**等于参数_e_(如果它是真实的)或window.event如果不是真的.如果参数_e_为null,则不是真的. (4认同)
  • 在 Chrome 中不再工作(已弃用):https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove_custom_messages_in_onbeforeunload_dialogs (4认同)
  • IE8中不支持@Blieque addEventListener.不要在没有阅读问题的情况下编辑人们的答案. (3认同)

jan*_*mon 24

看到这篇文章.您正在寻找的功能是onbeforeunload

示例代码:

  <script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法确定用户选择了"离开此页面"选项而不是"留在此页面上"? (2认同)

Rem*_*emi 6

与其烦人的确认弹出窗口,不如延迟一小段时间(毫秒)来成功地将未保存的数据成功发布到服务器,这是我很好的做法,我使用这样的虚拟文本向控制台进行管理:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server
Run Code Online (Sandbox Code Playgroud)

编辑: 另请参见Synchronous_AJAX以及如何使用jquery

  • 我不会在生产中使用它。console.log不是跨浏览器;每个postRequest都遭受前一个延迟(这也意味着该页面将在您的循环*计划的请求期间挂在那里);请求不是并行开始的;您不能保证真正发送您的请求。如果我被迫面对这个问题,那么如果只有一个请求,我会处理一个同步的ajax请求。对于多个请求,我将使用异步ajax请求和一个循环,该循环从请求的回调中检查结果(成功还是错误)。 (6认同)
  • 那绝对没有意义-1。javascript没有线程化,您正在做的事情是执行postRequest,然后暂停网站的计算而没有任何人不能做任何事情(包括您的postRequest,这是在计算暂停之前已经发送的)。 (2认同)