Recommended way to track client connection (detect browser close/redirection, etc)

I am trying to establish some kind of an active session when the user visits a particular page and I want to detect when this session closes (either by closing browser, or user moves to some other page, etc). This is because I want to do some clean up on the server when that session closes.

I found a good solution for the Hearbeat method on StackOverflow. However, I’ve got 2 concerns:

  1. That answer is quite old and I’m curious if there are better ways to do this now
  2. Hundreds of users pinging the server every 5 second does not sound too efficient.

On that same question, someone suggested using _session object like so:
this._session.socket.on("close", function() { /*do your thing*/});

But that’s not documented and I’m not sure how reliable that would be.


There is a package that I explored for this: https://github.com/mizzao/meteor-user-status
This works well but it does not track the session on a per page basis and does not fit my requirement.

So I am currently thinking of going with the Heartbeat method of pinging the server every few seconds but wanted to get other opinions on this.

Thanks

Try https://atmospherejs.com/socialize/user-presence, I think it will fit your use case very well.

The package seems to come at a good time :slight_smile: It does look good. I am still going through the docs but is there a way to send an extra piece of data from the client?

Basically, if there is any way I can identify in the server ‘onSessionDisconnected’ callback what this session was about (Iron router name of the route user was at OR some other custom data that I have on the client to identify the session)?

Thanks

In case someone else comes across this, I put this in my client-side Meteor.startup

// used to detect when the browser is closed
window.addEventListener('beforeunload', function (event) {
  // do stuff here
}, false)

// used to detect when the window loses focus -- e.g. user changes to another window or new tab
window.addEventListener("blur", function(event) {
    // do stuff here
  }, false);
1 Like