Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检测浏览器或选项卡关闭_Javascript_Jquery - Fatal编程技术网

Javascript 检测浏览器或选项卡关闭

Javascript 检测浏览器或选项卡关闭,javascript,jquery,Javascript,Jquery,是否有跨浏览器JavaScript/jQuery代码来检测浏览器或浏览器选项卡是否正在关闭,而不是由于单击了链接吗?如果我没有弄错,您想知道选项卡/窗口何时有效关闭。好吧,在Javascript中检测此类内容的唯一方法是onunload和onbeforeuload事件 不幸的是(或幸运的是?),当您通过链接或浏览器后退按钮离开站点时,也会触发这些事件。因此,这是我能给出的最好答案,我认为您无法在Javascript中检测到纯close。如果我错了,请纠正我。 <body onbeforeu

是否有跨浏览器JavaScript/jQuery代码来检测浏览器或浏览器选项卡是否正在关闭,而不是由于单击了链接吗?

如果我没有弄错,您想知道选项卡/窗口何时有效关闭。好吧,在
Javascript
中检测此类内容的唯一方法是
onunload
onbeforeuload
事件

不幸的是(或幸运的是?),当您通过
链接或浏览器后退按钮离开站点时,也会触发这些事件。因此,这是我能给出的最好答案,我认为您无法在Javascript中检测到纯
close
。如果我错了,请纠正我。


<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">

var myclose = false;

function ConfirmClose()
{
    if (event.clientY < 0)
    {
        event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
        setTimeout('myclose=false',10);
        myclose=true;
    }
}

function HandleOnClose()
{
    if (myclose==true) 
    {
        //the url of your logout page which invalidate session on logout 
        location.replace('/contextpath/j_spring_security_logout') ;
    }   
}
var myclose=false; 函数ConfirmClose() { 如果(event.clientY<0) { event.returnValue='您已关闭浏览器。是否要从应用程序注销?'; setTimeout('myclose=false',10); myclose=true; } } 函数HandleOnClose() { 如果(myclose==true) { //注销时使会话无效的注销页面的url 替换('/contextpath/j_-spring_-security_-logout'); } }
//这在IE7中起作用,如果您要关闭只有一个选项卡的选项卡或浏览器

$(window).unload( function () { alert("Bye now!"); } );
由于某些原因,基于Webkit的浏览器不符合对话框的规范。一个几乎相互交叉的例子与下面的例子很接近

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});
此示例用于处理所有浏览器。

试试这个, 我相信这对你会有用的

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
    $(function() {

        try{
            opera.setOverrideHistoryNavigationMode('compatible');
            history.navigationMode = 'compatible';
        }catch(e){}

        function ReturnMessage()
        {
            return "wait";
        }

        function UnBindWindow()
        {
            $(window).unbind('beforeunload', ReturnMessage);
        }

        $(window).bind('beforeunload',ReturnMessage );
    });
</script>

$(函数(){
试一试{
opera.setOverrideHistoryNavigationMode(“兼容”);
history.navigationMode='compatible';
}捕获(e){}
函数ReturnMessage()
{
返回“等待”;
}
函数UnBindWindow()
{
$(窗口).unbind('beforeunload',ReturnMessage);
}
$(window.bind('beforeunload',ReturnMessage));
});
简单解决方案

window.onbeforeunload = function () {
    return "Do you really want to close?";
};

很抱歉,我无法向现有答案之一添加注释,但如果您想实现一种警告对话框,我只想指出,任何事件处理程序函数都有一个参数-事件。在您的情况下,可以调用event.preventDefault()来禁止自动离开页面,然后发出您自己的对话框。我认为这比使用标准的丑陋和不安全的警报()更好。我个人基于kendoWindow对象(Telerik的Kendo UI,除了kendoGrid和kendoEditor之外,它几乎是完全开源的)实现了我自己的一组对话框。您还可以使用jQuery UI中的对话框。不过请注意,这些事情是异步的,您需要将一个处理程序绑定到每个按钮的onclick事件,但这一切都很容易实现

然而,我同意缺少真正的关闭事件是可怕的:例如,如果您只想在真正关闭的情况下重置后端的会话状态,这是一个问题

window.onbeforeunload = function ()
{       

    if (isProcess > 0) 
    {
        return true;       
    }   

    else
    { 
        //do something      
    }
}; 

如果您在浏览器中的任何进程中关闭窗口或刷新页面,此函数将显示一个确认对话框。此函数适用于所有浏览器。您必须在ajax进程中设置isProcess var。

尝试此操作。它会起作用的。不支持jquery卸载方法

window.onbeforeunload = function(event) {
    event.returnValue = "Write something clever here..";
};

没有事件,但有一个属性
window.closed
,在撰写本文时,所有主要浏览器都支持该属性。因此,如果您确实需要知道,您可以轮询窗口以检查该属性

if(myWindow.closed){do things}

注:
轮询任何内容通常都不是最佳解决方案。如果可能的话,应该使用
窗口.onbeforeunload
事件,唯一的警告是,如果您导航到其他链接,它也会触发。

我需要在浏览器或选项卡关闭时自动注销用户,而不是在用户导航到其他链接时。我也不希望在发生这种情况时显示确认提示。经过一段时间的努力,特别是在IE和Edge上,以下是我在基于IE的方法之后所做的事情(检查使用IE 11、Edge、Chrome和Firefox)

window.addEventListener("beforeunload", function (e) {
 var confirmationMessage = "tab close";

 (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
 sendkeylog(confirmationMessage);
 return confirmationMessage;                                //Webkit, Safari, Chrome etc.
}); 
首先,在JS中的
beforeunload
事件处理程序中启动服务器上的倒计时。ajax调用需要同步,IE和Edge才能正常工作。您还需要使用
return防止确认对话框显示如下:

    window.addEventListener("beforeunload", function (e) {        
      $.ajax({
          type: "POST",
          url: startTimerUrl,
          async: false           
      });
      return;
    });
<body onUnload="LogOff()">
启动计时器将
cancelLogout
标志设置为false。如果用户刷新页面或导航到另一个内部链接,服务器上的
cancelLogout
标志将设置为true。计时器事件结束后,它将检查
cancelLogout
标志,查看注销事件是否已取消。如果计时器已取消,则会停止计时器。如果浏览器或选项卡已关闭,则
cancelLogout
标志将保持为false,事件处理程序将注销用户


实现说明:我正在使用ASP.NET MVC 5,我正在用一个被覆盖的
控制器.OnActionExecuted()
方法取消注销。

我找到了一种方法,可以在我的所有浏览器上运行

在以下版本上测试: Firefox 57,Internet Explorer 11,Edge 41,最新的Chrome浏览器之一(不会显示我的版本)

注意:如果您以任何可能的方式离开页面(刷新、关闭浏览器、重定向、链接、提交…),onbeforeunload将触发。如果您只希望它发生在浏览器关闭时,只需绑定事件处理程序即可


对于类似的任务,您可以使用
sessionStorage
在本地存储数据,直到关闭浏览器选项卡

sessionStorage
对象仅存储一个会话的数据(当浏览器选项卡关闭时,数据将被删除)。()


解雇。
$(“#注意”)。单击(函数(){
//单击即可设置会话存储
setItem(“dismissNotice”、“Hello”);
$(“#通知”).remo
  $(document).ready(function(){         

        var validNavigation = false;

        // Attach the event keypress to exclude the F5 refresh (includes normal refresh)
        $(document).bind('keypress', function(e) {
            if (e.keyCode == 116){
                validNavigation = true;
            }
        });

        // Attach the event click for all links in the page
        $("a").bind("click", function() {
            validNavigation = true;
        });

        // Attach the event submit for all forms in the page
        $("form").bind("submit", function() {
          validNavigation = true;
        });

        // Attach the event click for all inputs in the page
        $("input[type=submit]").bind("click", function() {
          validNavigation = true;
        }); 

        window.onbeforeunload = function() {                
            if (!validNavigation) {     
                // ------->  code comes here
            }
        };

  });
<div id="Notice">
    <span title="remove this until browser tab is closed"><u>dismiss</u>.</span>
</div>
<script>
    $("#Notice").click(function() {
     //set sessionStorage on click
        sessionStorage.setItem("dismissNotice", "Hello");
        $("#Notice").remove();
    });
    if (sessionStorage.getItem("dismissNotice"))
    //When sessionStorage is set Do stuff...
        $("#Notice").remove();
</script>
var wrapper = function () { //ignore this

var closing_window = false;
$(window).on('focus', function () {
    closing_window = false; 
   //if the user interacts with the window, then the window is not being 
   //closed
});

$(window).on('blur', function () {

    closing_window = true;
    if (!document.hidden) { //when the window is being minimized
        closing_window = false;
    }
    $(window).on('resize', function (e) { //when the window is being maximized
        closing_window = false;
    });
    $(window).off('resize'); //avoid multiple listening
});

$('html').on('mouseleave', function () {
    closing_window = true; 
    //if the user is leaving html, we have more reasons to believe that he's 
    //leaving or thinking about closing the window
});

$('html').on('mouseenter', function () {
    closing_window = false; 
    //if the user's mouse its on the page, it means you don't need to logout 
    //them, didn't it?
});

$(document).on('keydown', function (e) {

    if (e.keyCode == 91 || e.keyCode == 18) {
        closing_window = false; //shortcuts for ALT+TAB and Window key
    }

    if (e.keyCode == 116 || (e.ctrlKey && e.keyCode == 82)) {
        closing_window = false; //shortcuts for F5 and CTRL+F5 and CTRL+R
    }
});

// Prevent logout when clicking in a hiperlink
$(document).on("click", "a", function () {
    closing_window = false;
});

// Prevent logout when clicking in a button (if these buttons rediret to some page)
$(document).on("click", "button", function () {
    closing_window = false;

});
// Prevent logout when submiting
$(document).on("submit", "form", function () {
    closing_window = false;
});
// Prevent logout when submiting
$(document).on("click", "input[type=submit]", function () {
    closing_window = false;
});

var toDoWhenClosing = function() {

    //write a code here likes a user logout, example: 
    //$.ajax({
    //    url: '/MyController/MyLogOutAction',
    //    async: false,
    //    data: {

    //    },
    //    error: function () {
    //    },
    //    success: function (data) {
    //    },
    //});
};


window.onbeforeunload = function () {
    if (closing_window) {
        toDoWhenClosing();
    }
};
var win = window.open('', '', 'width=200,height=50,left=200,top=50');
win.document.write(`<html>
   <head><title>CHILD WINDOW/TAB</title></head>
   <body><h2>CHILD WINDOW/TAB</h2></body>
</html>`);
win.addEventListener('load',() => {
    document.querySelector('.status').innerHTML += '<p>Child was loaded!</p>';
});
win.addEventListener('unload',() => {
    document.querySelector('.status').innerHTML += '<p>Child was unloaded!</p>';
    setTimeout(()=>{
        document.querySelector('.status').innerHTML +=  getChildWindowStatus();
    },1000);
});
win.document.close()
document.querySelector('.check-child-window').onclick = ()=> {
    alert(getChildWindowStatus());
}
function getChildWindowStatus() {
  if (win.closed) { 
      return 'Child window has been closed!';
  } else {
      return 'Child window has not been closed!';
  }
}
//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
  e = e || window.event;
  var localStorageTime = localStorage.getItem('storagetime')
  if(localStorageTime!=null && localStorageTime!=undefined){
    var currentTime = new Date().getTime(),
        timeDifference = currentTime - localStorageTime;

    if(timeDifference<25){//Browser Closed
       localStorage.removeItem('storagetime');
    }else{//Browser Tab Closed
       localStorage.setItem('storagetime',new Date().getTime());
    }

  }else{
    localStorage.setItem('storagetime',new Date().getTime());
  }
});
<body onUnload="LogOff()">
  function LogOff() {
        $.ajax({
            url: "/Account/LogOff",
            success: function (result) {

                                        }
               });
       }
window.onunload = function(){
    alert("The window is closing now!");
}