如何阻止页面在JS中卸载(导航)?

时间:2009-08-19 11:53:04

标签: javascript jquery events

有谁知道如何阻止页面重新加载或导航?

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;
            }
        });
    }
});

我目前正在开发电子商务网站,显示您未来订单的页面可以使用+/-按钮更改订购商品的数量。以这种方式改变数量实际上并没有改变订单本身,他们必须按下确认,因此提交一个积极的行动来改变订单。

然而,如果他们更改了数量并远离页面,我想警告他们他们这样做是为了防止发生意外,因为如果他们离开或刷新页面,更改的数量将会丢失。 / p>

在上面的代码中,我使用的是一个全局变量,默认情况下为false(仅适用于测试),当数量更改时,我将更新此变量为true,当他们确认更改时,我将设置它是假的。

如果警告为真并且页面已卸载,我会向他们提供一个确认框,如果他们拒绝他们想要留在此页面我需要停止卸载。 return false不起作用,它仍然允许用户导航(警报仅用于调试)

有什么想法吗?

7 个答案:

答案 0 :(得分:83)

onbeforeunload是你想要的;你的函数“应该将一个字符串值赋给Event对象的returnValue属性并返回相同的字符串”。有关详细信息,请查看MicrosoftMozilla中的文档。

您返回的字符串将被浏览器用于向用户显示自定义确认框,允许他们拒绝留在那里,如果他们愿意的话。必须采用这种方式来防止恶意脚本导致拒绝浏览器攻击。

答案 1 :(得分:66)

此代码根据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;
});

答案 2 :(得分:19)

您想使用 onbeforeunload 事件。

答案 3 :(得分:5)

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?";
}

答案 4 :(得分:4)

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 loose your unsaved changes';
  }
}
chrome,safari和opera

不支持

答案 5 :(得分:0)

this评论中所述,jQuery中没有任何内容绑定到beforeunload事件。

@ karim79:不,不是。 jQuery中没有任何绑定到beforeunload函数的东西。 “卸载”绑定到“卸载”事件。如果您不相信我,请搜索源;-) – NickFitz

因此,您必须使用纯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>

答案 6 :(得分:-5)

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