如何在用户离开页面时显示警告消息而不提交表单

时间:2014-09-05 06:07:24

标签: javascript jquery google-chrome mozilla

美好的一天 我想在用户离开页面时显示警告消息而不提交表单警告消息也应该在用户按F5刷新页面时显示 我已经做好了 当用户按下F5时,它会显示警告信息

$(function () {
    $(document).keydown(function (e) {
        if ((e.which || e.keyCode) == 116) {

            var FlagVal = $("#IsCaseInfoChanged").val();

            return "You have not saved your data. Do you really want to leave this page?";
        }
    });
});

以下代码显示警告消息 1.目前用于" IE"浏览器和" Chrome"浏览器如果您没有在地址栏中提供正确的URL,而不是向用户发出警告消息,以确保其工作正常。对于像Firefox和Safari这样的浏览器,它可以同时工作。

在Firefox浏览器中,它提供了浏览器特定的警告消息,而不是我们的服装消息。对于其他浏览器,它工作正常。 我该如何解决它。

 window.onbeforeunload = function (e) {

    /* Getting flag value for Browser if it has been set to true or not */

    /*if true show warning message*/

    var evtobj = window.event ? event : e;
    if (evtobj == e) {
        if (!evtobj.clientY) {
            return "You have not saved your data. Do you really want to leave this page?";
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你能试试吗,我还在努力吗?但只是告诉你想法

    function get_cookie ( cookie_name )
    {
        // http://www.thesitewizard.com/javascripts/cookies.shtml
        var cookie_string = document.cookie ;
        if (cookie_string.length != 0) {
            var cookie_value = cookie_string.match (
                            '(^|;)[\s]*' +
                            cookie_name +
                            '=([^;]*)' );
            return decodeURIComponent ( cookie_value[2] ) ;
        }
        return '' ;
    }

    $('document').ready(function(){
        var myCookie = get_cookie("validNavigationa");
        if (myCookie != null) {
            document.cookie = "validNavigationa=1";
        } else {
            document.cookie = "validNavigationa=2";
        }

        if(myCookie==2) {
            if(navigator.userAgent.indexOf("Firefox")>0) {
                if(confirm("My Custom Message")) {

                    document.cookie = "validNavigationa=1";
                    //window.close();  This will change depends the firefox version
                    window.onbeforeunload = function() { document.cookie = "validNavigationa=1"; }
                } else {
                    window.stop();
                }
            } else {
                window.onbeforeunload = function() { return "R u okay to Restart"; }; 
            }
        }

        setTimeout(function(){
            document.cookie = "validNavigationa=2";
        },100);
    });