I've used the event in other projects/games but it doesn't seem to be working on this one. onload event is working fine tho.
Script is linked on the bottom of the html before the < /body > tag
the code in client.js
(() => {
// Player Closes window
window.addEventListener("beforeunload", function (e) {
sock.emit('player-leave', player);
alert('window.addEventListener');
});
window.onbeforeunload = function(event) {
sock.emit('player-leave', player);
alert('window.onbeforeunload');
};
window.onunload = function(event) {
sock.emit('player-leave', player);
alert('window.onunload');
};
})();
Event doesn't pass throu and no alert is shown.
Link to git repository for full code: https://github.com/Tw1ster95/drawitgame
EDIT: I guess i found a way to use the socket id for the disconnect of player but i'm still wondering why doesn't it emit on beforeunload.
It is not the problem of onbeforeonload
. The reasons why alert
doesn't work is because modern browser will ignore the alert()
when doing beforeunload
.
The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during beforeunload event. See the HTML specification for more details.
Check it here
If you run your webpage and keep pressing a reloading key, you may able to see the error message Blocked alert() when beforeunload
in the console.