Javascript 识别刷新和关闭浏览器操作

Javascript 识别刷新和关闭浏览器操作,javascript,browser,Javascript,Browser,当我们刷新页面(F5或浏览器中的图标)时,它将首先刷新 触发ONUNLOAD事件。当我们关闭浏览器(右上角的X图标)时,它将 触发ONUNLOAD事件。 现在,当ONUNLOAD事件被触发时,无法区分刷新页面还是关闭浏览器。 如果您有任何解决方案,请给我。 <html> <body onunload="doUnload()"> <script> function doUnload(){ if (window.event.clientX <

当我们刷新页面(F5或浏览器中的图标)时,它将首先刷新 触发ONUNLOAD事件。当我们关闭浏览器(右上角的X图标)时,它将 触发ONUNLOAD事件。 现在,当ONUNLOAD事件被触发时,无法区分刷新页面还是关闭浏览器。 如果您有任何解决方案,请给我。


<html>
<body onunload="doUnload()">
<script>
   function doUnload(){
     if (window.event.clientX < 0 && window.event.clientY < 0){
       alert("Window closed");
     }
     else{
       alert("Window refreshed");
     }
   }
</script>
</body>
</html>
函数doUnload(){ if(window.event.clientX<0&&window.event.clientY<0){ 警报(“窗口关闭”); } 否则{ 警报(“窗口刷新”); } }
我以前的解决方案在IE中适用。window.event对于IE以外的浏览器是未定义的,因为“event”在IE中是全局定义的,与其他浏览器不同。对于其他浏览器,您需要提供事件作为参数。而且clientX不是为firefox定义的,我们应该使用pageX

尝试这样的东西…应该适用于IE和firefox这个

<html>
<body>
<script type="text/javascript">

window.onunload = function(e) {
// Firefox || IE
e = e || window.event;

var y = e.pageY || e.clientY;

if(y < 0)  alert("Window closed");
else alert("Window refreshed");

}
</script>
</body>
</html>

window.onunload=函数(e){
//Firefox | | IE
e=e | | window.event;
变量y=e.pageY | e.clientY;
如果(y<0)警报(“窗口关闭”);
else警报(“窗口刷新”);
}

不幸的是,正如这里的一些答案所建议的那样,检查事件的
clientY
/
pageY
值并不是确定用户是否由于关闭页面而触发
卸载
事件的可靠方法

当您单击浏览器的关闭按钮时,
clientY
/
pageY
的原因是因为关闭按钮位于文档顶部上方(即像素0上方),但“重新加载”按钮也是如此,这意味着单击“重新加载”按钮也会导致
clientY
/
pageY
的值为负值

沿着检查事件x坐标的路径往下走也是有问题的,因为浏览器关闭按钮并不总是在窗口的右侧(例如,在OS x中它位于左侧),而且窗口可以通过关闭其选项卡或通过键盘来关闭。

有一个解决方案

我想在关闭选项卡或浏览器窗口时断开服务器上的用户连接,但在重新加载页面时则不想断开连接(您可能希望区分重新加载/关闭事件的不同目的,但您可能会从我的解决方案中受益)。基于HTML5的本地存储和客户机/服务器AJAX通信,我完成了以下过程:

  • 在页面上,将
    onunload
    添加到
    窗口
    以下处理程序(伪javascript):

  • 在您的页面上,将
    正文上的
    onload
    添加到以下处理程序(伪javascript):

    函数myLoad(事件){
    if(window.localStorage){
    var t0=Number(window.localStorage['myUnloadEventFlag']);
    如果(isNaN(t0))t0=0;
    var t1=new Date().getTime();
    var持续时间=t1-t0;
    如果(持续时间)是浏览器重新加载(因此取消断开连接请求)
    askServerToCancelDisconnectionRequest();//异步AJAX调用
    }否则{
    //上一次卸载事件是针对选项卡/窗口关闭=>做任何你想做的事情(我在这里什么都不做)
    }
    }
    } 
    
  • 在服务器上,收集列表中的断开请求,并设置一个定时线程,定期检查列表(我每20秒使用一次)。一旦断开请求超时(即5秒已过),断开用户与服务器的连接。如果同时收到断开连接请求取消,则相应的断开连接请求将从列表中删除,以便用户不会断开连接

  • 如果要区分选项卡/窗口关闭事件和后续链接或提交的表单,此方法也适用。只需在包含链接和表单的每个页面以及每个链接/表单登录页面上放置两个事件处理程序

    请注意,我使用
    unload
    事件而不是
    beforeUnload
    事件来正确管理指向附件的链接:当用户单击指向附件的链接(例如PDF文件)时,将调度
    beforeUnload
    事件,然后引发打开/保存弹出窗口,仅此而已(浏览器不会更改显示的页面,也不会发送
    unload
    事件)。如果我使用
    beforeUnload
    事件(就像我以前所做的那样),我会在没有页面更改时检测到页面更改

    这种方法仅限于支持HTML5本地存储的浏览器,因此您可能会对MSIE7等旧浏览器使用特定的方法


    基于
    事件的其他方法。clientY
    不可靠,因为当单击重新加载或选项卡/窗口关闭按钮时,该值为负值,当使用键盘快捷键重新加载(例如F5、Ctrl-R等)和关闭窗口(例如Alt-F4)时,该值为正值.依赖事件X位置也不可靠,因为每个浏览器上的按钮都不在同一位置(例如,左侧的关闭按钮).

    使用window.onbeforeunload事件使案例导航离开页面,但它将包括刷新或锚定标记…使用验证标志进行相同操作,流程的一个示例是URL检查(初始URL=当前URL)或使用键码进行F5检查以进行刷新,如果锚定标记使用bind()

    注*如果使用Chrome,钥匙代码可能会导致问题

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <title>Test Page</title>
    
    <style type='text/css'>
    body {
        font-family: sans-serif;
    }
    </style>
    <script src="jquery-1.9.1.js" type='text/javascript'></script>
    <script type='text/javascript'>
    var valid=false;
    function wireUpEvents() {
    
    if(valid){
    alert("Page Refreshed or Redirected");
    }else{
    
    window.onbeforeunload = askWhetherToClose;
    
    }
    function askWhetherToClose(event) {
    
    if(!valid){
    
        var msg;
    
        msg = "You're leaving the page, do you really want to?";
        event = event || window.event;
        event.returnValue = msg;
        return msg;
    }}
    $(document).bind('keypress', function(e) { 
     if (e.keyCode == 116){ 
    
     // or you can insert some code to check page refresh
     valid = true; 
    
    //wireUpEvents();
     } 
     }); 
     $("a").bind("click", function() {
    //To check redirection using Anchor tags  
     valid = true; 
     //wireUpEvents();
     }); 
     }
    $(document).ready(function() { 
     wireUpEvents(); 
    
     });
    </script>
    </head>
    <body>
    <p>Close the browser window, or navigate to <a href="http://stackoverflow.com">StackOverflow</a></p>
    </body>
    </html>
    
    
    测试页
    身体{
    字体系列:无衬线;
    }
    var-valid=false;
    函数wireUpEvents(){
    如果(有效){
    警报(“页面刷新或重定向”);
    }否则{
    window.onbeforeunload=askWhetherToClose;
    }
    函数askWhetherToClose(事件){
    如果(!有效){
    var-msg;
    msg=“您要离开页面,真的要离开吗?”;
    event=event | | window.event;
    event.returnValue=msg;
    返回味精;
    }}
    $(文档).bind('keypress',函数(e){
    如果(e.keyCode==116){
    //或者您可以插入一些代码来检查页面引用
    
    function myLoad(event) {
        if (window.localStorage) {
            var t0 = Number(window.localStorage['myUnloadEventFlag']);
            if (isNaN(t0)) t0=0;
            var t1=new Date().getTime();
            var duration=t1-t0;
            if (duration<10*1000) {
                // less than 10 seconds since the previous Unload event => it's a browser reload (so cancel the disconnection request)
                askServerToCancelDisconnectionRequest(); // asynchronous AJAX call
            } else {
                // last unload event was for a tab/window close => do whatever you want (I do nothing here)
            }
        }
    } 
    
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <title>Test Page</title>
    
    <style type='text/css'>
    body {
        font-family: sans-serif;
    }
    </style>
    <script src="jquery-1.9.1.js" type='text/javascript'></script>
    <script type='text/javascript'>
    var valid=false;
    function wireUpEvents() {
    
    if(valid){
    alert("Page Refreshed or Redirected");
    }else{
    
    window.onbeforeunload = askWhetherToClose;
    
    }
    function askWhetherToClose(event) {
    
    if(!valid){
    
        var msg;
    
        msg = "You're leaving the page, do you really want to?";
        event = event || window.event;
        event.returnValue = msg;
        return msg;
    }}
    $(document).bind('keypress', function(e) { 
     if (e.keyCode == 116){ 
    
     // or you can insert some code to check page refresh
     valid = true; 
    
    //wireUpEvents();
     } 
     }); 
     $("a").bind("click", function() {
    //To check redirection using Anchor tags  
     valid = true; 
     //wireUpEvents();
     }); 
     }
    $(document).ready(function() { 
     wireUpEvents(); 
    
     });
    </script>
    </head>
    <body>
    <p>Close the browser window, or navigate to <a href="http://stackoverflow.com">StackOverflow</a></p>
    </body>
    </html>
    
        $(window).bind('unload', function () {
            if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
                console.log('firefox delete');
                var data = { async: false };
                endSession(data);
                return null;
            }
            else {
                console.log('NON-firefox delete');
                var data = { async: true };
                endSession(data);
                return null;
            }
        });
    
        function endSession(data) {
            var id = 0
    
            if (window) { // closeed
                id=1
            }
    
            $.ajax({
                url: '/api/commonAPI/'+id+'?Action=ForceEndSession',
                type: "get",
                data: {},
                async: data.async,
                success: function () {
                    console.log('Forced End Session');
                }
            });
        }
    
    export class BootstrapComponent implements OnInit {
    
      validNavigation = 0;
    
      constructor(
        private auth: AuthenticationService
      ) { }
    
      ngOnInit() {
        const self = this;
        self.registerDOMEvents();
      }
    
      registerDOMEvents() {
        const self = this;
        window.addEventListener('unload', () => {
          if (self.validNavigation === 0) {
            self.endSession();
          }
        });
        document.addEventListener('keydown', (e) => {
          const key = e.which || e.keyCode;
          if (key === 116) {
            self.validNavigation = 1;
          }
        });
      }
    
      endSession() {
        const self = this;
        self.auth.clearStorage();
      }
    }
    
    window.addEventListener('unload', () => {
      open('refresh-close-detector.html', '', 'width=100,height=100');
    })
    
    let rDown = false;
    window.addEventListener("keydown", event => {
        if (event.key == 'r')
            rDown = true;
    })
    window.addEventListener("keyup", event => {
        if (event.key == 'r')
            rDown = false;
    })
    
    window.addEventListener("onunload", () => {
        if (!rDown) {
            // code that only gets run when the window is closed (or
            // some psychopath reloads by actually clicking the icon)
        }
    });
    
    if (sessionStorage.getItem('reloaded') != null) {
        console.log('page was reloaded');
    } else {
        console.log('page was not reloaded');
    }
    
    sessionStorage.setItem('reloaded', 'yes');