在beforeunload事件处理程序中停止卸载页面

在用户导航页面代码之前,检查他是否编辑了一些表单字段。 如果他这样做,我会显示一个带有YesNo按钮的模态窗口。 如果他单击否,则模态应该关闭,用户仍然在该窗口上。 如果是 – 保存更改并卸载。

  $(window).bind('beforeunload', function(){ // check if any field is dirty if ($('div.form').dirtyForms('isDirty')) { var modalParams = { Content: 'You have some unsaved changes, proceed?' OnSave: navigateAndSave, OnCancel: cancelNavigate } ShowModal(modalParams); } }) function navigateAndSave() { // Do stuff }; function cancelNavigate() { // Stop page from unloading and close the modal }; 

那么我可以在cancelNavigate做什么来阻止页面卸载?

这是可能的,但前提是用户单击页面中的超链接。 如果用户使用浏览器离开页面,他们将获得默认的浏览器对话框,该对话框没有保存选项。

Dirty Forms会自动附加(并删除处理程序)到beforeunload事件,因此您尝试创建另一个事件处理程序肯定会失败。 使用脏表格时,不应该这样做。

你没有提到你想使用哪个modal dialog架,所以我将只使用jQuery UI对话框展示一个例子。 集成其他对话框架是类似的。 为此,您可能需要查看现有预构建对话框的源代码。

此外,您的用例有点短。 如果用户想要离开并忽略更改,该怎么办? 我添加了一个示例,其中包含另外一个选项。

        Change one of the fields below, then click "Go to Google" to try to navigate away. 
First name:
Last name:
Go to Google

该示例使用自定义事件绑定附加到onRefireClick事件处理程序,该处理程序在choice.proceed = truechoice.proceed = true ,但在false时则触发。

那是不可能的。

您只能显示短信以及在页面上继续或离开的选项。

请访问此链接以获取更多信息: https : //developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

 window.onbeforeunload = funcRef 
  • funcRef是对函数或函数表达式的引用。
  • 该函数应将字符串值赋给Event对象的returnValue属性并返回相同的字符串。

例:

 window.onbeforeunload = function(e) { return 'Dialog text here.'; }; 

在用户决定留在页面上后,您可以显示您的模态,但我认为它的建议将在当时被击败。

如其他人所述,您可以通过聆听页面上链接和表单上的点击和按键事件来拦截导航,但是当用户尝试手动输入URL时,这将不允许您显示任何对话框,关闭选项卡,关闭窗口,按下重新加载,后退或前进按钮等。

beforeunload事件以这种方式设计,以保护用户免受恶意脚本的攻击。

如果允许那种控制某人可以将浏览器锁定在所需页面中,则不允许您离开或关闭窗口。

编辑。:

我已经设法显示一个确认对话框,通过在unloadunload附加到2个事件,其工作方式几乎与您想要的一样。 它适用于Internet Explorer 11,Firefox 40和Safari 5.1 for Windows(我现在可以确认):

 var alreadyTriggered = false; function onQuit() { if (alreadyTriggered) return true; alreadyTriggered = true; if (confirm('Sure?')) { alert('OK'); } else { alert('Cancel'); } } window.onbeforeunload = onQuit; window.onunload = onQuit; 
 You can reload the page to test it here. 

我相信你只需要在事件上调用preventDefault。

  $(window).bind('beforeunload', function(e){ // check if any field is dirty if ($('div.form').dirtyForms('isDirty')) { var modalParams = { Content: 'You have some unsaved changes, proceed?' OnSave: navigateAndSave, OnCancel: e.preventDefault(); } ShowModal(modalParams); } }) function navigateAndSave() { // Do stuff };