繁体   English   中英

使用 jquery/Javascript 在浏览器关闭或选项卡关闭时执行注销

[英]Perform logout on browser close or tab close using jquery/Javascript

我需要在浏览器关闭或选项卡关闭时注销用户。 我试过使用下面的代码,它工作正常,除了以下内容:1.) 当我点击浏览器刷新按钮时,它仍然注销 2.) 当我在浏览器中更改 URL 并按 Enter 时它仍然注销两者以上是不可取的,我想防止。 任何人都可以建议如何? 这是我的脚本:

 var validNavigation = false; function wireUpEvents() { window.onbeforeunload = function(e) { if (!validNavigation) { endSession(); } } //Hits the server and invalidates the session function endSession() { $.ajax({ url : "performLogout..", type : "GET", async: false, success : function(response) {}, error: function(response) {} }); } //On click of F5 document.onkeydown = function disableKeys() { if( typeof event != 'undefined' ) { if(event.keyCode == 116) { validNavigation = true; event.keyCode = 0; //return false; //return false if u want to disable refresh } } }; // Attach the event click for all links in the page $("a").on("click", function() { validNavigation = true; }); // Attach the event submit for all forms in the page $("form").on("submit", function() { validNavigation = true; }); // Attach the event click for all inputs in the page $("input[type=submit]").on("click", function() { validNavigation = true; }); $("select#select-id").on("change", function() { validNavigation = true; }); } // Wire up the events as soon as the DOM tree is ready $(document).ready(function() { wireUpEvents(); });

谢谢

对于数字 2,无法区分用户关闭选项卡和用户键入要前往的新 URL。 我要问你的问题是,如果他们在地址栏中输入google.com ,这与他们关闭选项卡并导航的效果相同,为什么不将他们注销? 您是否考虑过他们登录,在您的网站上打开一个新选项卡,然后关闭该选项卡。 原始选项卡仍处于打开状态,但您想将其注销? 在假设用户的意图之前考虑边缘情况。

对于您的场景,如果每个会话只有一个选项卡,您可能需要查看SessionStorage ,它仅在浏览器窗口关闭之前在本地保存信息。 所有新选项卡都将是会话的实例。

也许一个好的方法是在用户离开页面时将会话标记为paused无论什么条件,然后在加载新页面时resume他们的会话。 在这种环境中,您需要在服务器上实现简单的垃圾收集以丢弃旧会话。

总而言之,除非您 100% 确定他们已完成,否则不要注销用户。 多一点努力几乎总是值得更好的用户体验。 否则,您将失去有价值的用户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM