简体   繁体   English

防止浏览器重新加载按钮单击 beforeunload 事件

[英]Prevent beforeunload event from browser reload button click

I have a script which executes on page beforeunload to trigger a web method on tab close / browser close.我有一个脚本,它在页面 beforeunload 上执行以在选项卡关闭/浏览器关闭时触发 Web 方法。 functionality of this script is to trigger a webmethod on a page beforeunload.此脚本的功能是在卸载之前在页面上触发 web 方法。 i wanted to prevent the script method from executing on f5 button click and able to do that.我想阻止脚本方法在 f5 按钮单击时执行并且能够做到这一点。 but now i need to prevent the script method from executing on browser reload button click (mostly chrome) but could'nt do it.但现在我需要阻止脚本方法在浏览器重新加载按钮点击(主要是 chrome)时执行,但无法做到。 i have shared the script below.我已经分享了下面的脚本。 any suggestion is much appreciated.任何建议都非常感谢。

       var IsFunction5KeyPressed = false;

        // .... Tab & Browser Close Events ....
        $(window).bind('beforeunload', function (e) {
            if (!IsFunction5KeyPressed) {                  
                $.ajax({
                    type: "POST",
                    url: "Page.aspx/WebMethod1",
                    data: '{name: "' + "test" + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function () { IsFunction5KeyPressed = false;  },
                    error: function (response) { }
                });
            }
        });

        document.onkeydown = fkey;
        document.onkeypress = fkey
        document.onkeyup = fkey;

        var wasPressed = false;

        function fkey(e) {
            e = e || window.event;
            if (wasPressed) return;

            if (e.keyCode == 116) {
                IsFunction5KeyPressed = true
                wasPressed = true;
            }   
        }

As far as I know, a page refresh will always trigger the beforeunload since the page actually unloads.据我所知,页面刷新总是会触发beforeunload因为页面实际上是卸载的。 At that moment, I don't think you can detect the difference between a close and a page reload.在那一刻,我认为您无法检测关闭和页面重新加载之间的区别。

You can detect it at a later time, if you use local storage of some sort: javascript beforeunload detect refresh versus close如果您使用某种本地存储,您可以稍后检测它: javascript beforeunload 检测刷新与关闭

The only thing that you can do is to prevent the default behaviour if the user presses the f5 key.如果用户按下 f5 键,您唯一能做的就是阻止默认行为。

Please try and let me know if this works for you请尝试让我知道这是否适合您

        function fkey(e) {
            e = e || window.event;    
            if (e.keyCode == 116) {
                e.preventDefault();
            }   
        }

In this case, user won't be able to refresh the screen by clicking f5在这种情况下,用户将无法通过单击 f5 来刷新屏幕

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM