Add a listener to .info/connected
and add/remove childs using push()
/remove()
.
Example:
javascriptonValue(ref(db, '.info/connected'), snapshot => { if (snapshot.val()) { let key = push(ref(db, 'concurrent'), {connected: true}) onDisconnect(key).remove() } })
When the page loads, the listener will push a new object into the concurrent
branch.
JSON{ "concurrent": { "AsZjsk" : { "connected": true } } }
When the user closes the website or is inactive, onDisconnect()
function will remove the branch automatically.
The total number of online users is the number of childs on the concurrent branch.
Example:
javascriptonValue(ref(db, 'concurrent'), snapshot => { if(snapshot.val()){ let concurrent = snapshot.val() let total = Oject.keys(concurrent).length console.log(`There are ${total} concurrent (online) users!`) } })
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.