Removing someone from a user hash on navigating away from a page / page close

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);
    })

Problem courtesy of: Jack

Solution

… 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

Solution courtesy of: ajax333221

Discussion

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.

Discussion courtesy of: Daniele B

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.

Discussion courtesy of: josh3736

This recipe can be found in it’s original form on Stack Over Flow
.

稿源:Node.js Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Removing someone from a user hash on navigating away from a page / page close

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录