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!