lalit
lalit

Reputation: 55

Is there any way to kill session on closing browser? I have used the onunload and onbeforeunload event. but it doesnt work

I have used the (window.onunload) and (window.onbeforeunload) event for capturing browser close event to kill session. but it doesn't work for me in chrome. Is there any way to do?

Upvotes: 2

Views: 770

Answers (1)

Amadan
Amadan

Reputation: 198436

Normal async XMLHttpRequest (including fetch) tend to be cancelled as the page closes. The usual workaround has been to make synchronous requests.

However, there's a new way to do it: navigator.sendBeacon. It was designed with pretty much that exact purpose in mind - it will queue a request to be executed even after the page is closed.

window.addEventListener("unload", function() {
  navigator.sendBeacon("/logout");
});

It still doesn't work on all browsers, so if you care about the lag-behinders you might want to test if it is available, and use the above-mentioned workaround if not.

Upvotes: 4

Related Questions