首页 > 解决方案 > 如何检查应用程序的最后一个浏览器选项卡是否已关闭

问题描述

我们正在使用加密的 cookie 来保持用户的会话在多个选项卡中处于活动状态。

如果用户关闭浏览器,cookie 将被删除,不会有任何麻烦。但是,如果用户打开了 2 个选项卡,一个是应用程序选项卡,另一个是某个任意站点的选项卡,并且用户关闭了应用程序选项卡,则当用户打开新的应用程序选项卡时 cookie 仍然存在,因此,用户会话仍处于活动状态,不会强制他再次登录。

所以我的想法如下:

  1. 通过在浏览器 cookie 中存储计数值来跟踪打开的选项卡。
  2. 如果打开新选项卡,则增加 cookie
  3. 如果选项卡关闭,则减少 cookie
  4. 如果浏览器刷新,则保持 cookie 计数不变

对于第 2 到 4 项,我使用window.performance.navigation.type属性来确定选项卡是否已加载或刷新。首次打开选项卡时,navigation.type正确指示 的类型0,即TYPE_NAVIGATE。但是,如果刷新同一个选项卡,该类型仍然指示值为 0,并且只有在第二次刷新后,它才正确切换为 1,即TYPE_RELOAD. 所以这个 0 和 1 之间的错误解释会导致 cookie 计算不正确。

下面是我的代码,也许是关于出了什么问题的任何想法或反馈,或者可能是确定最后一个选项卡是否关闭的更好方法的指南?

var checkTabs = function () {
    //This method gets called at the start of the application

    var isRefresh = window.performance.navigation.type === window.performance.navigation.TYPE_RELOAD;

    //The getCookie and setCookie methods are custom functions to retrieve a browser cookie and its value, and set the retrieved cookie value.
    var tabCookie = getCookie({ name: "WS:T" });

    //If the cookie is not found, we create a new cookie with an initialized value of 0
    if (!tabCookie)
        tabCookie = { name: "WS:T", value: 0 };

    var increment = tabCookie.value;

    //If the navigation type is a navigate and not a refresh, we increment the cookie value    
    if (!isRefresh)
        increment = parseInt(tabCookie.value, 10) + 1;

    setCookie({ name: "WS:T", value: increment, expiry: moment().subtract(1, "days").format("YYYY-MM-DD HH:mm") });
};

监听器beforeunload被添加到窗口对象并引用下面的方法:

var beforeUnloadTab = function (e) {
        var isRefresh = window.performance.navigation.type === window.performance.navigation.TYPE_RELOAD;
        if (!isRefresh) {
    //Only decrement the cookie if the tab is closed and not refreshed.
            var tabCookie = getCookie({ name: "WS:T" });
            var decrement = parseInt(tabCookie.value, 10) - 1;

            if (decrement === 0) {
                //If the last tab is being closed, perform the necessary clearing of all session values etc.
            }

            setCookie({ name: "WS:T", value: decrement, expiry: moment().subtract(1, "days").format("YYYY-MM-DD HH:mm") });
        }
    };

标签: jquerycookies

解决方案


推荐阅读