拦截页面退出事件 [英] Intercept page exit event

查看:116
本文介绍了拦截页面退出事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When editing a page within my system, a user might decide to navigate to another website and in doing so could lose all the edits they have not saved.

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

I would like to intercept any attempt to go to another page and prompt the user to be sure they want this to happen since they could potentially lose their current work.

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

Gmail does this in a very similar way. For example, compose a new email, start typing into the message body and enter a new location in the address bar (say twitter.com or something). It will prompt asking "Are you sure?"

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

Ideas how to replicate this? I'm targeting IE8, but would like to be compatible with FF & Chrome also.

推荐答案

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

Similar to Ghommey's answer, but this also supports old versions of IE and 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;
};

这篇关于拦截页面退出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆