In JavaScript, I am instantiating a WebSocket like this:
var webSocket = new WebSocket('wss://example.com:8081');
webSocket.onclose = function () {
// Custom function
}
However, does code inside of my custom onclose
function run if the user closes their browser window or quits their browser? I tried placing an Ajax call there and a webSocket.send() function, but neither ran successfully.
If onclose
does not run when the window is closed or the user quits their browser, what would be the best way to run custom code on the server once the user disconnects? My best guess right now is that code has to be executed from the server-side – in other words the running WebSocket server (written in php in my case) needs custom code in an internal onClose
method.
onclose fires when the socket connection is closed, which isnt necessarily when your window or browser closes. Theoretically when another window with a socket closed it should fire, but it wont fire if its the own window.
Id advise adding an event listener for beforeunload, link below, which fires when the page and its resources are about to be unloaded
https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
Example
window.addEventListener("beforeunload", function (event) {
});
Additionally, onunload may be a useful event to listen to