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


70

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

jQuery(函数($){

    / *全局卸载通知* /
    警告=真;

    如果(警告){
        $(window).bind(“ unload”,function(){ 
            如果(confirm(“是否要离开此页面”)== true){
                //他们按了确定
                警报('确定');
            }其他{
                //他们按下了取消
                警报('取消');
                返回false;
            }
        });
    }
});

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

但是,如果他们更改了数量并离开了页面,我想警告他们,以防万一,这是意外的情况,因为如果更改数量会导致他们离开或刷新页面,则丢失。

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

如果警告是正确的并且该页面已卸载,那么我会向他们提供一个确认框,如果他们说不,他们希望保留在该页面上,则需要停止该页面的卸载。return false不起作用,它仍然允许用户导航(警报仅在此处调试)

有任何想法吗?


Answers:


85

onbeforeunload是你想要的那个 您的函数“应将字符串值分配给Event对象的returnValue属性并返回相同的字符串”。查看MicrosoftMozilla的文档以了解详细信息。

浏览器将使用您返回的字符串为用户提供一个自定义确认框,从而允许他们拒绝选择停留在那儿的用户。必须采取这种方式来防止恶意脚本引起“浏览器拒绝”攻击。


3
应该注意的是,如果您使用jQuery绑定事件,则应绑定到该事件beforeunload(除去on字符串的一部分)
jgillman 2012年

这在现代浏览器上不再起作用。您不能在显示的框中放置任何自定义消息。(明显出于安全原因)
mlwacosmos

70

此代码按照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;
});

9
Why the downvote? I answered and added to the topic. The warning variable is there to illustrate a proof of concept. Toggle it off or remove it. I'm sure most users won't copy code verbatim from this site and use it as is.
crafter

7
I'm guessing the downvote is because you set the warning variable and then don't use it in your submit function, e.g. just use warning=false rather than window.onbeforeunload = null
Bob Vale

2
The warning isn't needed in the event of a submit action...only if the user tries to leave the page WITHOUT submitting.
jcorry

20

you want to use the onbeforeunload event.


@scunliffe - in jQuery 'unload' means 'onbeforeunload', that's what she's doing.
karim79

17
@karim79: no it doesn't. There isn't anything in jQuery that binds to the beforeunload function; "unload" binds to the "unload" event. Search the source if you don't believe me ;-)
NickFitz

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

Isn't supported in chrome, safari and opera


4
Isn't supported on Chrome? I'm pretty sure SO presents such a dialog to me when I entered something in the editor (I'm using Chrome 4.0.206.0 on Linux)
Joachim Sauer

You need a multi line string.
Justin Liu

0

As said in this comment, nothing in jQuery binds to the beforeunload event.

@ 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>


-4

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


@MathieuK-我投票赞成,因为我认为您是对的,但您可能应该1)举一个例子或2)修改问题中的代码以在其他人出现之前采纳您的建议;)
karim79

14
preventDefault不会对unload事件产生任何影响-脚本无法取消卸载,因为这将允许恶意站点劫持浏览器窗口。
NickFitz

preventdefault未在卸载事件上实现
Jens Meinecke 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.