jquery - 如何检查应用程序的最后一个浏览器选项卡是否已关闭
问题描述
我们正在使用加密的 cookie 来保持用户的会话在多个选项卡中处于活动状态。
如果用户关闭浏览器,cookie 将被删除,不会有任何麻烦。但是,如果用户打开了 2 个选项卡,一个是应用程序选项卡,另一个是某个任意站点的选项卡,并且用户关闭了应用程序选项卡,则当用户打开新的应用程序选项卡时 cookie 仍然存在,因此,用户会话仍处于活动状态,不会强制他再次登录。
所以我的想法如下:
- 通过在浏览器 cookie 中存储计数值来跟踪打开的选项卡。
- 如果打开新选项卡,则增加 cookie
- 如果选项卡关闭,则减少 cookie
- 如果浏览器刷新,则保持 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") });
}
};
解决方案
推荐阅读
- windows - Powershell 命令不再工作 - 仅以管理员身份运行
- reactjs - 使用 React Hooks 和 Context 检查电子邮件是否已经存在于 Firestore 的集合中
- azure - Azure 数据工厂中的复制活动替代方案
- cypress - 我们可以使用赛普拉斯断言按钮是可操作的而不单击它吗
- java - Kafka 事务生产者抛出“在 60000 毫秒内初始化事务状态时超时已过期”
- javascript - 删除基于文本而不是值的选项
- sql - 非当前行上的 SQL 连接
- c# - 如何从函数返回转换的数据类型变量?
- r - 如何在 R 命令中使用迭代变量?
- javascript - 如何更改 vue-apexcharts 中的特定线条颜色,如 contidional 颜色更改?