Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

322
Views
window onunload/onbeforeunload events don't work?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!