如何显示"您确定要离开此页面吗?" 什么时候改变?

Shi*_*mmy 253 html javascript confirm message onbeforeunload

在stackoverflow中,如果您开始进行更改,那么您尝试离开页面,会出现一个javascript确认按钮并询问:"您确定要离开此页面吗?" blee blah bloo ...

有没有人以前实现过这个,我如何跟踪提交的更改?我相信我自己可以做到这一点,我正在努力学习专家们的良好做法.

我尝试了以下但仍然无法正常工作:

<html>
<body>
    <p>Close the page to trigger the onunload event.</p>
    <script type="text/javascript">
        var changes = false;        
        window.onbeforeunload = function() {
            if (changes)
            {
                var message = "Are you sure you want to navigate away from this page?\n\nYou have started writing or editing a post.\n\nPress OK to continue or Cancel to stay on the current page.";
                if (confirm(message)) return true;
                else return false;
            }
        }
    </script>

    <input type='text' onchange='changes=true;'> </input>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

任何人都可以发一个例子吗

Kei*_*ith 351

更新(2017年)

现代浏览器现在考虑将自定义消息显示为安全隐患,因此已将从所有消息中删除.浏览器现在只显示通用消息.由于我们不再需要担心设置消息,因此它很简单:

// Enable navigation prompt
window.onbeforeunload = function() {
    return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
Run Code Online (Sandbox Code Playgroud)

请阅读下面的旧版浏览器支持.

更新(2013年)

原始答案适用于IE6-8和FX1-3.5(这是我们在2009年编写时的目标),但现在已经过时了,并且在大多数当前浏览器中都无法使用 - 我已离开它在下面供参考.

window.onbeforeunload所有浏览器都没有一致的处理.它应该是一个函数引用而不是一个字符串(如原始答案所述),但它可以在较旧的浏览器中使用,因为对大多数浏览器的检查似乎是是否分配了任何内容onbeforeunload(包括返回的函数null).

您设置window.onbeforeunload为函数引用,但在旧版浏览器中,您必须设置returnValue事件而不是仅返回字符串:

var confirmOnPageExit = function (e) 
{
    // If we haven't been passed the event get the window.event
    e = e || window.event;

    var message = 'Any text will block the navigation and display a prompt';

    // For IE6-8 and Firefox prior to version 4
    if (e) 
    {
        e.returnValue = message;
    }

    // For Chrome, Safari, IE8+ and Opera 12+
    return message;
};
Run Code Online (Sandbox Code Playgroud)

confirmOnPageExit如果您希望用户在没有消息的情况下继续,则不能执行检查并返回null.您仍然需要删除事件以可靠地打开和关闭它:

// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;

// Turn it off - remove the function entirely
window.onbeforeunload = null;
Run Code Online (Sandbox Code Playgroud)

原始答案(2009年工作)

打开它:

window.onbeforeunload = "Are you sure you want to leave?";
Run Code Online (Sandbox Code Playgroud)

要关闭它:

window.onbeforeunload = null;
Run Code Online (Sandbox Code Playgroud)

请记住,这不是正常事件 - 您无法以标准方式绑定它.

要检查值?这取决于您的验证框架.

在jQuery中,这可能是(非常基本的例子):

$('input').change(function() {
    if( $(this).val() != "" )
        window.onbeforeunload = "Are you sure you want to leave?";
});
Run Code Online (Sandbox Code Playgroud)

  • 这将是这样的:$('input:text').change(function(){window.onbeforeunload = $('input:text [value!=""]').length> 0?"warning":null ;}); (4认同)
  • 为了在表单提交时停止警报,我使用了`$("#submit_button").click(function(){window.onbeforeunload = null;});`.我最初使用按钮的onclick事件,但不是很好,它也不适用于IE8. (3认同)

Sør*_*org 37

onbeforeunload微软主义是我们要一个标准的解决方案,但要知道,浏览器支持参差不齐最接近; 例如,对于Opera,它仅适用于版本12及更高版本(截至本文撰写时仍为测试版).

此外,为了获得最大的兼容性,您需要做的不仅仅是返回一个字符串,如Mozilla Developer Network所述.

示例:定义以下两个用于启用/禁用导航提示的功能(参见MDN示例):

function enableBeforeUnload() {
    window.onbeforeunload = function (e) {
        return "Discard changes?";
    };
}
function disableBeforeUnload() {
    window.onbeforeunload = null;
}
Run Code Online (Sandbox Code Playgroud)

然后定义一个这样的表单:

<form method="POST" action="" onsubmit="disableBeforeUnload();">
    <textarea name="text"
              onchange="enableBeforeUnload();"
              onkeyup="enableBeforeUnload();">
    </textarea>
    <button type="submit">Save</button>
</form>
Run Code Online (Sandbox Code Playgroud)

这样,只有在用户更改了文本区域时才会向用户发出警告,并且在他实际提交表单时不会提示用户.


ssh*_*how 19

要在Chrome和Safari中使用,您必须这样做

window.onbeforeunload = function(e) {
    return "Sure you want to leave?";
};
Run Code Online (Sandbox Code Playgroud)

参考:https://developer.mozilla.org/en/DOM/window.onbeforeunload


Sam*_*ron 18

使用JQuery这个东西很容易做到.因为你可以绑定到集合.

它不足以进行onbeforeunload,你只想触发导航,如果有人开始编辑东西.

  • => 500内部错误.这就是为什么链接在SO上被弃用的原因.下注直到修复. (14认同)
  • 似乎无法点击@jonstjohn的博文.也许他会成为一个朋友并指出我们正确的方向?:d (2认同)
  • 虽然此链接可能会回答这个问题,但最好在此处包含答案的基本部分并提供参考链接.如果链接的页面发生更改,则仅链接的答案可能会无效. (2认同)
  • [Jon St John的原始链接](http://jonstjohn.com/node/23)已被破坏,因此我将其更新为[Wayback Machine](http://web.archive.org/web/20130730025134/ http://jonstjohn.com/node/23)它的版本.可以在许多其他网站中找到链接的内容,但我想最好"保留"Sam添加的链接 (2认同)

Dev*_*las 13

jquerys'afterunload'对我很有用

$(window).bind('beforeunload', function(){
    if( $('input').val() !== '' ){
        return "It looks like you have input you haven't submitted."
    }
});
Run Code Online (Sandbox Code Playgroud)


Car*_*l G 11

如果有任何数据输入到表单中,这是一种简单的方法来呈现消息,而不是在提交表单时显示消息:

$(function () {
    $("input, textarea, select").on("input change", function() {
        window.onbeforeunload = window.onbeforeunload || function (e) {
            return "You have unsaved changes.  Do you want to leave this page and lose your changes?";
        };
    });
    $("form").on("submit", function() {
        window.onbeforeunload = null;
    });
})
Run Code Online (Sandbox Code Playgroud)


law*_*tog 11

对于正在寻找简单解决方案的新人,只需尝试Areyousure.js


Mik*_*ike 7

扩展Keith已经很棒的答案:

自定义警告消息

要允许自定义警告消息,您可以将其包装在如下函数中:

function preventNavigation(message) {
    var confirmOnPageExit = function (e) {
        // If we haven't been passed the event get the window.event
        e = e || window.event;

        // For IE6-8 and Firefox prior to version 4
        if (e)
        {
            e.returnValue = message;
        }

        // For Chrome, Safari, IE8+ and Opera 12+
        return message;
    };
    window.onbeforeunload = confirmOnPageExit;
}
Run Code Online (Sandbox Code Playgroud)

然后用你的自定义消息调用该函数:

preventNavigation("Baby, please don't go!!!");
Run Code Online (Sandbox Code Playgroud)

再次启用导航

要重新启用导航,您需要做的就是设置window.onbeforeunloadnull.在这里,它包含在一个可以在任何地方调用的简洁小功能:

function enableNavigation() {
    window.onbeforeunload = null;
}
Run Code Online (Sandbox Code Playgroud)

使用jQuery将其绑定到表单元素

如果使用jQuery,这很容易绑定到表单的所有元素,如下所示:

$("#yourForm :input").change(function() {
    preventNavigation("You have not saved the form. Any \
        changes will be lost if you leave this page.");
});
Run Code Online (Sandbox Code Playgroud)

然后允许提交表单:

$("#yourForm").on("submit", function(event) {
    enableNavigation();
});
Run Code Online (Sandbox Code Playgroud)

动态修改形式:

preventNavigation()并且enableNavigation()可以根据需要绑定到任何其他函数,例如动态修改表单,或单击发送AJAX请求的按钮.我这样做是通过向表单添加一个隐藏的输入元素:

<input id="dummy_input" type="hidden" />
Run Code Online (Sandbox Code Playgroud)

然后,只要我想阻止用户导航,我就会触发对该输入的更改以确保preventNavigation()执行:

function somethingThatModifiesAFormDynamically() {

    // Do something that modifies a form

    // ...
    $("#dummy_input").trigger("change");
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Tre*_*nis 5

标准规定可以通过取消beforeunload事件或将返回值设置为非空值来控制提示。它还指出作者应该使用 Event.preventDefault() 而不是 returnValue,并且向用户显示的消息是不可自定义的

截至69.0.3497.92,Chrome尚未达到标准。不过,已提交错误报告,审核正在进行中。Chrome 要求通过引用事件对象来设置 returnValue,而不是处理程序返回的值。

作者有责任跟踪是否已进行更改;可以使用变量或确保仅在必要时处理事件来完成。

window.addEventListener('beforeunload', function (e) {
    // Cancel the event as stated by the standard.
    e.preventDefault();
    // Chrome requires returnValue to be set.
    e.returnValue = '';
});
    
window.location = 'about:blank';
Run Code Online (Sandbox Code Playgroud)