1

I'm building a Node.js / Socket.io project.

I have a hash of Users based on their websocket id. When a user makes the following request i'd like to add them to a group of users viewing that page.

app.get('/board/:id', function(req, res){}

I'd like to keep something like

Browsing = { username : id, username : id, ... }

However i'm unsure how to remove a user lets say if they navigate off the page. Is there some kind of function that gets called upon page leave?

Partial Solution:

The following seems to do the trick on Chrome:
   $(window).unload(function(){
      var username = $('#username').text();
      var pid = currentProject;

      var data = {
        username: username,
        id : pid
      }

      socket.emit('leaving-page', data);
    })
Jack
  • 15,614
  • 19
  • 67
  • 92
  • I don't think there's any 100% reliable way to do that. Consider for example what happens when the client computer experiences a sudden power failure. – Pointy Jan 23 '12 at 15:43

3 Answers3

2

... Is there some kind of function that gets called upon page leave? ...

Yes, but it is not reliable.

The way the people keep track of who is online and who isn't, is usually like this:

  • Add the time when the user last refreshed/visited a page
  • set a limit to you consider them offline
ajax333221
  • 11,436
  • 16
  • 61
  • 95
  • But you are free to still use the 'page leave' function to make it more time accurate. However, you should really backup with something in case the 'page leave' function fails. – ajax333221 Jan 23 '12 at 16:01
  • Thanks, i'll try a combination of your answer and @Daniele Bs answer :) – Jack Jan 23 '12 at 16:06
2

You could intercept the event which corresponds to leaving a page. There are several ways to do it, have a look at the following links and let me know if any suits your needs and if I can answer any more explicit questions about them:

with the last link you could do something like this:

    $(window).unload(function() {
      //remove the user from your json object with delete json_object[key];
    });

Hope this helps.

Community
  • 1
  • 1
Daniele B
  • 3,117
  • 2
  • 23
  • 46
1

Since you're using Socket.io, the server will know when the user has left the page because the socket will be disconnected. Simply listen for the disconnect event.

io.sockets.on('connection', function (socket) {

  ...

  socket.on('disconnect', function () {
    // The user on `socket` has closed the page
  });

});

Better yet, take advantage of namespaces and let Socket.io handle all of the connection/disconnection (it's doing it anyway -- no need to duplicate effort).

On the client,

socket = io.connect('http://example.com/pagename');

pagename need not point to a valid URL on your domain – it's just the namespace you'll use in the server code:

io.sockets.clients('pagename')

Gets you all of the clients currently connected to the pagename namespace.

josh3736
  • 139,160
  • 33
  • 216
  • 263