简体   繁体   中英

How to logout the user when user closes the browser or tab

window.onbeforeunload event not sending ajax request on Server side

I want to logout the user when user closes the browser or tab. I have implemented the window.onbeforeunload event but on this method ajax request is not working.

 window.onbeforeunload = function() { var d = { userid: 123 }; $.ajax({ type: 'POST', url: 'https://example.com/api/logout', data: d, async: false }); return null; }; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> need html perhaps 

As you already thought of, your action is asynchronous and therefor not stopping the browser to be closed.

The async: false is not supported anymore. Not by jquery nor by browsers.

http://api.jquery.com/jquery.ajax/

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

and therefor you must cancel the event until the success event as stated here.

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Still a number of questions around this (two browser windows, what happens next, what if it fails,

 function handleMyUnload(e) { // Cancel the event e.preventDefault(); // Chrome requires returnValue to be set e.returnValue = ''; var d = { userid: 123 }; $.ajax({ type: 'POST', url: 'https://example.com/api/logout', data: d, async: false }).done(function(data, textStatus, jqXHR) { // ajax is done, so remove the handler window.removeEventListener("beforeunload", handleMyUnload, false); // leave it to you to determine what happens next (close, reload, navigate etc.) here }).fail(function(){ // do what? }); return null; } window.addEventListener("beforeunload", handleMyUnload, false); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> need html perhaps 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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