如何停止在 JS 中卸载(导航离开)页面?

有人知道如何阻止页面重新加载或导航离开吗?

jQuery(function($) {


/* global on unload notification */
warning = true;


if(warning) {
$(window).bind("unload", function() {
if (confirm("Do you want to leave this page") == true) {
//they pressed OK
alert('ok');
} else {
// they pressed Cancel
alert('cancel');
return false;
}
});
}
});

我目前在一个电子商务网站工作,页面显示您的未来订单有能力改变订购的项目数量使用 +/-按钮。以这种方式改变数量实际上并不会改变订单本身,他们必须按确认键,因此要采取积极的行动来改变订单。

然而,如果他们已经改变了数量和导航离开的页面,我想警告他们,他们这样做的情况下,这是一个意外,因为改变的数量将丢失,如果他们导航离开或刷新页面。

在上面的代码中,我使用了一个全局变量,它在默认情况下为 false (在测试中只为 true) ,当一个数量发生变化时,我将更新这个变量为 true,当他们确认这些变化时,我将把它设置为 false。

如果警告是真实的,页面被卸载,我提供给他们一个确认框,如果他们说不,他们想留在这个页面上,我需要阻止它从卸载。Return false 不起作用,它仍然允许用户导航离开(警报仅用于调试)

有什么想法吗?

106125 次浏览

您希望使用 在卸货之前事件。

尝试使用 e.preventDefault()而不是返回 false。‘ e’将是 卸货回调函数的第一个参数。

onbeforeunload是你想要的; 你的函数 “应该为 Event 对象的 returValue 属性分配一个字符串值,并返回相同的字符串”。查看来自 微软Mozilla的文档了解详细信息。

您返回的字符串将被浏览器用于为用户提供一个自定义确认框,允许他们拒绝停留在那里,如果他们这样选择。这样做是为了防止恶意脚本导致拒绝浏览器攻击。

window.onbeforeunload = function() {
if (warning) {
return `You have made changes on this page that you have not yet confirmed.
If you navigate away from this page you will lose your unsaved changes`;
}
}

不支持铬,狩猎和歌剧

该代码根据 Natalie 的建议发出警告,但是如果页面上的表单已经提交,则禁用该警告。使用 JQuery。

var warning = true;
window.onbeforeunload = function() {
if (warning) {
return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";
}
}


$('form').submit(function() {
window.onbeforeunload = null;
});
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?";
}

正如在 这个注释中所说,jQuery 中没有绑定到 beforeunload事件。

@ karim79: 不,没有。JQuery 中没有绑定到 before unload 函数的内容; “ unload”绑定到“ unload”事件。如果你不相信我,就去查一下来源; ——尼克 · 菲茨

因此,必须使用纯 Javascript 将函数绑定到 beforeunload事件。

var warning = true;
$("form").submit(function() {
warning = false;
});
$('#exit').click(function() {
window.location.replace('https://stacksnippets.net/js')
});
window.onbeforeunload = function() {
if(warning) {
return true;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form>
<input type="submit">
</form>