Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
window.onbeforeunload event executing early?

So I am building a real-time chatroom, and this is my code so far. I am trying to create exit messages, in that when someone closes the tab or goes to a different page, it inserts a message to the database.

This is what I have so far:

<?php
session_start();
require('./essentials.php');
welcome_message(0, 11, true); //custom function that I wrote in ./essentials.php
?>

<html style="background-color:#202020;">

<head>
    <title>Programming - Parity Chatroom</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src='./socket.js'></script>
    <script type='text/javascript'>
        websocket.onopen = function() {
            alert('Connected to server!');
            conn.send("Someone joined!");
        }
        websocket.onmessage = function() {
            if (!document.hasFocus()) {
                var audio = new Audio("./notification.wav");
                audio.play();
            }
        }
        websocket.onclose = function() {
            setTimeout(function() {
                window.location.reload();
            }, 5000);
        }
        window.onbeforeunload = function() {
            conn.close(1000, 'Closed page');
            <?php exit_message(); /* function to insert exit message to db */ ?>
        }
    </script>
</head>
<FRAMESET cols="20%,*">
    <FRAME src="sidebar.php" id='sidebar' style='overflow:hidden'>
    <FRAMESET rows="*,9%">
        <FRAME src="messages.php" id='messages'>
        <FRAME src="newmessage.php" id='newmessage' style='overflow:hidden'>
    </FRAMESET>
</FRAMESET>
</html>

So the code runs just fine, but I think there is an issue with the order in which the code runs. Specifically, the javascript onbeforeunload event seems to fire whenever I visit the page. I suspect that this has to do with the fact that PHP code loads and executes when the page loads, considering that it is a server-side language.
Is there a way to slow that down and make the script run in order?


Any help would be greatly appreciated!

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda