如何处理浏览器标签页关闭事件的角度?只是接近,没有刷新 [英] How can I handle browser tab close event in Angular? Only close, not refresh

查看:168
本文介绍了如何处理浏览器标签页关闭事件的角度?只是接近,没有刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标,删除用户的cookie时,浏览器标签页关闭。

这可能吗?我可以在不刷新的情况下,处理浏览器标签关闭事件?

如果我用 beforeunload 卸载事件,功能触发,如果用户刷新页面,我不希望这样,我想只要运行时关闭的标签。

我怎么能做到这一点的角?


解决方案

这是可悲的是,不是一个简单的问题来解决。但它可以做到的。下面的答案是从许多不同的答案SO合并。

简单的部分:
Knowning正在被销毁的窗口。您可以使用 onunload的事件句柄来检测这一点。

棘手的问题:

检测,如果它是一个更新,链接,后续或所需的窗口关闭的事件。删除链接如下,并提交表单是很容易的:

  VAR inFormOrLink;
$('A')生活('点击',功能(){inFormOrLink = TRUE;});
$('形式')的bind('提交',函数(){inFormOrLink = TRUE;});$(窗口).bind('beforeunload',函数(eventObject)传递{
    VAR的returnValue =不确定;
    如果(!inFormOrLink){
        的returnValue =你真的要关闭吗?
    }
    eventObject.returnValue =的returnValue;
    返回的returnValue;
});

可怜的人的解决方案

检查 event.clientY event.clientX 确定单击触发事件是什么。

 函数doUnload(){
 如果(window.event.clientX&℃,放大器;&放大器; window.event.clientY℃,){
   警报(窗口关闭);
 }
 其他{
   警报(窗口刷新);
 }
}

Y轴不工作的原因时,键盘快捷键来重新加载(如F5,按Ctrl-R,...)和窗口关闭它的负对重载或标签/窗口关闭按钮的点击,和积极的(如: ALT-F4)。 X轴,因为不同的浏览器有不同的按钮展示位置是没有用的。但是,如果你限制,然后运行该事件的坐标直通一系列的if-别人的可能是你最好的选择的。当心,这肯定是不可靠的。

参与的解决方案

(从朱利安Kronegg )使用HTML5的本地存储和客户端/服务器AJAX通讯。警告:这种方法仅限于支持HTML5本地存储浏览器

在你的页面,添加 onunload的窗口下面的处理程序

 函数myUnload(事件){
    如果(window.localStorage){
        //标志页面被卸
        。window.localStorage ['myUnloadEventFlag'] =新的日期()的getTime();
    }    //通知我们要断开用户在几秒钟的服务器(我用5秒)
    askServerToDisconnectUserInAFewSeconds(); //同步AJAX调用
}

然后添加一个 onloadon 身体下面的处理程序

 函数myLoad(事件){
    如果(window.localStorage){
        变种T0 =号码(window.localStorage ['myUnloadEventFlag']);
        如果(isNaN(T0))T0 = 0;
        VAR T1 =新的日期()的getTime()。
        VAR持续时间= T1-T0;
        如果(持续时间小于10 * 1000){
            //不到10秒,因为previous Unload事件= GT;这是一个浏览器重装(所以取消断开连接请求)
            askServerToCancelDisconnectionRequest(); //异步AJAX调用
        }其他{
            //最后卸载事件是一个标签/窗口关闭=>做什么
        }
    }
}


  

在服务器上,收集在一个列表中的下线请求并设置
  计时器线程检查其定期列表(我用
  每20秒)。一旦断开请求超时(即5
  秒都消失了),断开服务器的用户。如果一个
  断开请求取消在其间接收所述
  对应断开请求被从列表中删除,以便
  用户将不会被断开。


  
  

此方法也适用,如果你想区分
  标签/窗口关闭事件,随后链接或提交表单。你刚才
  需要把两个事件处理程序,其中包含链接的每一页上
  和形式和每一个环节/表单登陆页面上。


关闭评论(双关语意):

由于您希望在关闭窗口删除的cookie,我假设它为$ P $在将来的会话中使用pvent他们。如果这是一个正确的假设,上述方法将工作做好。你保持无效cookie中的服务器上(一旦客户端断开),当客户端创建一个新的会话时,JS会在发送的cookie在默认情况下,在这一点上,你知道它从较早的会话,删除它并可选提供新的在客户端上进行设置。

My goal, remove user cookies when browser tab closed.

Is it possible? Can I handle browser tab close event without refresh case?

If I use beforeunload or unload events, function triggered when user refresh page, I don't want this, I want just run when closed tab.

How can I do this in Angular?

解决方案

This is, tragically, not a simple problem to solve. But it can be done. The answer below is amalgamated from many different SO answers.

Simple Part: Knowning that the window is being destroyed. You can use the onunload event handle to detect this.

Tricky Part:

Detecting if it's a refresh, link follow or the desired window close event. Removing link follows and form submissions is easy enough:

var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });

$(window).bind('beforeunload', function(eventObject) {
    var returnValue = undefined;
    if (! inFormOrLink) {
        returnValue = "Do you really want to close?";
    }
    eventObject.returnValue = returnValue;
    return returnValue;
}); 

Poor-man's Solution

Checking event.clientY or event.clientX to determine what was clicked to fire the event.

function doUnload(){
 if (window.event.clientX < 0 && window.event.clientY < 0){
   alert("Window closed");
 }
 else{
   alert("Window refreshed");
 }
}

Y-Axis doesn't work cause it's negative for clicks on reload or tab/window close buttons, and positive when keyboard shortcuts are used to reload (e.g. F5, Ctrl-R, ...) and window closing (e.g. Alt-F4). X-Axis is not useful since different browsers have differing button placements. However, if you're limited, then running the event coordinates thru a series of if-elses might be your best bet. Beware that this is certainly not reliable.

Involved Solution

(Taken from Julien Kronegg) Using HTML5's local storage and client/server AJAX communication. Caveat: This approach is limited to the browsers which support HTML5 local storage.

On your page, add an onunload to the window to the following handler

function myUnload(event) {
    if (window.localStorage) {
        // flag the page as being unloading
        window.localStorage['myUnloadEventFlag']=new Date().getTime();
    }

    // notify the server that we want to disconnect the user in a few seconds (I used 5 seconds)
    askServerToDisconnectUserInAFewSeconds(); // synchronous AJAX call
}

Then add a onloadon the body to the following handler

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
        }
    }
} 

On the server, collect the disconnection requests in a list and set a timer thread which inspects the list at regular intervals (I used every 20 seconds). Once a disconnection request timeout (i.e. the 5 seconds are gone), disconnect the user from the server. If a disconnection request cancelation is received in the meantime, the corresponding disconnection request is removed from the list, so that the user will not be disconnected.

This approach is also applicable if you want to differentiate between tab/window close event and followed links or submitted form. You just need to put the two event handlers on every page which contains links and forms and on every link/form landing page.

Closing Comments (pun intended):

Since you want to remove cookies when the window is closed, I'm assuming it's to prevent them from being used in a future session. If that's a correct assumption, the approach described above will work well. You keep the invalidated cookie on the server (once client is disconnected), when the client creates a new session, the JS will send the cookie over by default, at which point you know it's from an older session, delete it and optionally provide a new one to be set on the client.

这篇关于如何处理浏览器标签页关闭事件的角度?只是接近,没有刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆