如何在 Angular 中处理浏览器选项卡关闭事件?只关闭不刷新 [英] How can I handle browser tab close event in Angular? Only close, not refresh

查看:23
本文介绍了如何在 Angular 中处理浏览器选项卡关闭事件?只关闭不刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在浏览器选项卡关闭时删除用户 cookie.

有可能吗?我可以在没有刷新的情况下处理浏览器选项卡关闭事件吗?

如果我使用 beforeunloadunload 事件,函数在用户刷新页面时触发,我不想要这个,我只想在关闭标签时运行.

如何在 Angular 中执行此操作?

解决方案

不幸的是,这不是一个要解决的简单问题.但这是可以完成的.下面的答案来自许多不同的 SO 答案.

简单部分:知道窗口正在被破坏.您可以使用 onunload 事件句柄来检测这一点.

棘手的部分:

检测是刷新、链接跟踪还是所需的窗口关闭事件.删除链接和表单提交很容易:

var inFormOrLink;$('a').live('click', function() { inFormOrLink = true; });$('form').bind('submit', function() { inFormOrLink = true; });$(window).bind('beforeunload', function(eventObject) {var returnValue = 未定义;如果(!inFormOrLink){returnValue = "你真的要关闭吗?";}eventObject.returnValue = returnValue;返回返回值;});

穷人的解决方案

检查 event.clientYevent.clientX 以确定点击什么来触发事件.

function doUnload(){if (window.event.clientX <0 && window.event.clientY <0){alert("窗口关闭");}别的{alert("窗口刷新");}}

Y 轴不起作用,因为它对重新加载或选项卡/窗口关闭按钮的点击是负面的,当使用键盘快捷键来重新加载(例如 F5、Ctrl-R、...)和窗口关闭(例如Alt-F4).X 轴没有用,因为不同的浏览器有不同的按钮位置.但是,如果您有限,那么通过一系列 if-else 运行事件坐标可能是您最好的选择.请注意,这肯定不可靠.

涉及的解决方案

(取自 Julien Kronegg)使用 HTML5 的本地存储和客户端/服务器 AJAX沟通.警告:此方法仅限于支持 HTML5 本地存储的浏览器.

在您的页面上,将 onunload 添加到以下处理程序的窗口中

function myUnload(event) {如果(window.localStorage){//将页面标记为正在卸载window.localStorage['myUnloadEventFlag']=new Date().getTime();}//在几秒内通知服务器我们要断开用户连接(我用了 5 秒)askServerToDisconnectUserInAFewSeconds();//同步 AJAX 调用}

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

function myLoad(event) {如果(window.localStorage){var t0 = Number(window.localStorage['myUnloadEventFlag']);如果 (isNaN(t0)) t0=0;var t1=new Date().getTime();var 持续时间=t1-t0;如果(持续时间<10*1000){//距离上一次卸载事件不到 10 秒 =>这是浏览器重新加载(因此取消断开连接请求)askServerToCancelDisconnectionRequest();//异步 AJAX 调用} 别的 {//上次卸载事件是针对选项卡/窗口 close =>做任何事}}}

<块引用>

在服务器上,收集一个列表中的断开请求并设置一个定期检查列表的计时器线程(我使用每 20 秒).一旦断开连接请求超时(即 5秒过去了),断开用户与服务器的连接.如果一个同时收到断开连接请求取消,相应的断开请求从列表中删除,以便用户不会断开连接.

如果您想区分,这种方法也适用选项卡/窗口关闭事件和跟踪链接或提交的表单.你刚才需要在每个包含链接的页面上放置两个事件处理程序和表单以及每个链接/表单登录页面.

结束评论(双关语):

因为您想在窗口关闭时删除 cookie,所以我假设这是为了防止在以后的会话中使用它们.如果这是一个正确的假设,则上述方法将运行良好.您将无效的 cookie 保留在服务器上(一旦客户端断开连接),当客户端创建新会话时,JS 将默认发送 cookie,此时您知道它来自旧会话,将其删除并可选择提供要在客户端上设置新的.

My goal is 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.

这篇关于如何在 Angular 中处理浏览器选项卡关闭事件?只关闭不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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