Search code examples
meteormeteor-accounts

Track if a user is on the current document


For a discussion site I would like to display the users which are not only logged in but also currently have the discussion site active. So if a user is logged in my Meteor application but surfs somewhere else his name would be greyed out on the discussion site.

To get who is logged in is trivial, but how can I know which users are on my page?


Solution

  • You are looking for the Page Visibility API. It does exactly what you want: With it, you can detect if the current document is being browsed by the user or not, and of course you can detect changes in the visibility via events.

    Here's a basic example:

    //Inside a Meteor.startup, onRendered callback...
    document.addEventListener('visibilityChange', changeUserState);
    
    function changeUserState() { //You can define that higher to respect hoisting
      if (document.hidden) {
        setUserInactive();
      }
      else {
        setUserActive();
      }
    }
    

    Note that according to the MDN page this won't work on IE < 10...