簡體   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