title: emitting a message to node.js after page close
body: <p>So I'm pretty new to it, so I apologize if I this is an entirely wrong approach of doing this, but I am currently programming a little chat application using node.js with express and socket.io. I managed to get a login message logged to the console but I am really struggling with the logout one. When a user opens up the page I take the roomname aswell as the username out of a cookie and send it to the server like shown here:</p>
  
  <pre><code>var socket = io();
  var roomname = readCookie('Roomname');
  var nickname = readCookie('Nickname');
  var data = {'type': 'user', 'channel': roomname, 'user': nickname, 'data': "joined"};
  
  socket.emit('chat', data);
  </code></pre>
  
  <p>After that I filter the message on the server side and send the answer to all clients like this:</p>
  
  <pre><code>case 'user':
    io.emit('chat/' + msg.channel, {type: 'user', user: msg.user, data: msg.data});
    break;
  </code></pre>
  
  <p>I always send the string "chat" followed by the roomname as a channel name so only the users that are in the right rooms can see the message. After that I sort out what kind of message was received by the client side:</p>
  
  <pre><code>case 'user':
    console.log(msg.user + " just " + msg.data + " the room!");
    break;
  </code></pre>
  
  <p>Now the only thing I need to do is somehow getting the room- and username to the server side once the user closes the page so I can send the message but with "left". (like this)</p>
  
  <pre><code>var data = {'type': 'user', 'channel': roomname, 'user': nickname, 'data': "left"};
  
  socket.emit('chat', data);
  </code></pre>
  
  <p>My approach was finding an event that fires the code at the right time and I have been looking through stack overflow for a good hour now and I just couldn't find anything that did the job. I've tryed out all the variations of <code>window.onbeforeunload</code> I could find and none of them seemed to work. I could log some stuff to the console with some of them but I was never able to emit a message to the server side. I am aware that this may not be possible in the way I would like it to, but I really ran out of ideas what to try next. Can someone help me out?</p>