在用户导航之前,页面代码会检查他是否编辑了某些表单字段。如果他这样做,我会显示一个带有Yes
和No
按钮的模态窗口。如果他单击否,则模态应该关闭,用户仍然在该窗口上。如果是 - 保存更改并卸载。
$(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
中做些什么来阻止页面卸载?
答案 0 :(得分:2)
这是可能的,但前提是用户单击页面中的超链接。如果用户使用浏览器导航离开页面,他们将获得默认的浏览器对话框,该对话框没有保存选项。
Dirty Forms会自动附加(并删除处理程序)到beforeunload
事件,因此您创建另一个事件处理程序的尝试肯定会失败。使用脏表格时,不应该这样做。
你没有提到你想要使用哪个模态对话框架,所以我将只使用jQuery UI对话框展示一个例子。集成其他对话框架是类似的。为此,您可能需要查看existing pre-built dialogs的源代码。
另外,您的用例有点短边。如果用户想要离开并忽略更改,该怎么办?我添加了一个示例,其中包含一个额外的选项。
<html>
<head>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.ui/1.11.3/jquery-ui.min.css" />
</head>
<body>
<script type="text/javascript" src="//cdn.jsdelivr.net/g/jquery@1.11.3,jquery.ui@1.11.3,jquery.dirtyforms@2.0.0"></script>
<script type="text/javascript">
$(document).ready(function() {
// This is required by jQuery UI dialog
$('body').append('<div id="dirty-dialog" style="display:none;" />');
// This must be called before the first call to .dirtyForms
$(document).bind('bind.dirtyforms', function (ev, events) {
var originalOnRefireClick = events.onRefireClick;
events.onRefireClick = function (ev) {
if (saveForm) {
// TODO: Replace this with your AJAX function
// to save the form.
alert('saving form...');
}
originalOnRefireClick(ev);
};
});
// Flag indicating whether or not to save the form on close.
var saveForm = false;
$('.mainForm').dirtyForms({
dialog: {
// Custom properties to allow overriding later using
// the syntax $.DirtyForms.dialog.title = 'custom title';
title: 'Are you sure you want to do that?',
proceedAndSaveButtonText: 'Save Changes & Continue',
proceedAndCancelButtonText: 'Cancel Changes & Continue',
stayButtonText: 'Stay Here',
preMessageText: '<span class="ui-icon ui-icon-alert" style="float:left; margin:2px 7px 25px 0;"></span>',
postMessageText: '',
width: 650,
// Dirty Forms Methods
open: function (choice, message) {
$('#dirty-dialog').dialog({
open: function () {
// Set the focus on close button. This takes care of the
// default action by the Enter key, ensuring a stay choice
// is made by default.
$(this).parents('.ui-dialog')
.find('.ui-dialog-buttonpane button:eq(2)')
.focus();
},
// Whenever the dialog closes, we commit the choice
close: choice.commit,
title: this.title,
width: this.width,
modal: true,
buttons: [
{
text: this.proceedAndSaveButtonText,
click: function () {
// Indicate the choice is the proceed action
choice.proceed = true;
// Pass a custom flag to indicate to save the data first
// in the onRefireClick event
saveForm = true;
$(this).dialog('close');
}
},
{
text: this.proceedAndCancelButtonText,
click: function () {
// Indicate the choice is the proceed action
choice.proceed = true;
// Pass a custom flag to indicate not to save the data
// in the onRefireClick event
saveForm = false;
$(this).dialog('close');
}
},
{
text: this.stayButtonText,
click: function () {
// We don't need to take any action here because
// this will fire the close event handler and
// commit the choice (stay) for us automatically.
$(this).dialog('close');
}
}
]
});
// Inject the content of the dialog using jQuery .html() method.
$('#dirty-dialog').html(this.preMessageText + message + this.postMessageText);
},
close: function () {
// This is called by Dirty Forms when the
// Escape key is pressed, so we will close
// the dialog manually. This overrides the default
// Escape key behavior of jQuery UI, which would
// ordinarily not fire the close: event handler
// declared above.
$('#dirty-dialog').dialog('close');
}
}
});
});
</script>
Change one of the fields below, then click "Go to Google" to try to navigate away.
<form class="mainForm" action="jqueryui.html">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
<a href="http://www.google.com/">Go to Google</a>
</body>
</html>
该示例使用custom event binding附加到onRefireClick
事件处理程序,该事件处理程序在choice.proceed = true
时触发,但在false
时触发。
答案 1 :(得分:1)
那是不可能的。
您只能显示短信以及继续浏览页面或离开的选项。
请参阅此链接以获取更多信息:https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
window.onbeforeunload = funcRef
funcRef
是对函数或函数表达式的引用。- 该函数应将字符串值赋给
returnValue
对象的Event
属性,并返回相同的字符串。示例:
window.onbeforeunload = function(e) { return 'Dialog text here.'; };
在用户决定留在页面上之后,您可以显示您的模态,但我认为它的提议将在那时失败。
正如其他人所说,您可以通过聆听页面上链接和表单上的点击和按键事件来拦截导航,但是当用户尝试手动输入URL时,这将不允许您显示任何对话框,关闭选项卡,关闭窗口,按下重新加载,后退或前进按钮等。
beforeunload
事件的设计方式是保护用户免受恶意脚本的攻击。</ p>
如果允许某人控制某人可以将浏览器锁定在所需的页面中,则不允许您离开或关闭窗口。
修改:强>
通过附加到2个事件beforeunload
和unload
,我设法显示了一个与您想要的工作方式基本相同的确认对话框。它适用于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 <a href="javascript: location.reload();">reload the page</a> to test it here.
这取决于确认对话框导致的JS事件循环的中断,并且无法使用自定义对话框使其工作,因为页面将在用户有机会与之交互之前更改或关闭。
仍然无法避免页面更改或关闭,也无法在Chrome中使用此功能。这在Firefox中也不起作用,事件未被用户交互触发。
答案 2 :(得分:-1)
我相信你只需要在事件上调用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
};