Firebase Auth & Realtime Database Apps · Lekcja

Wykrywanie obecności i statusu online

Twórz wskaźniki stanu online/offline działające na żywo, korzystając z mechanizmu obecności Realtime Database, procedur obsługi onDisconnect i specjalnego węzła .info/connected, aby niezawodnie odzwierciedlać stan połączenia.

Lekcja 4 z 413 kroki

Wykrywanie obecności i statusu online to bezpłatna lekcja Firebase Auth & Realtime Database Apps na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Firebase Auth & Realtime Database Apps, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Firebase Auth & Realtime Database Apps zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

What Is Presence

Presence means knowing which users are currently online. Chat apps, collaborative tools, and games all rely on it to show 'active now' indicators.

Realtime Database has special features that make presence robust even when a client disconnects unexpectedly.

The Connection Challenge

The hard part is the ungraceful disconnect: a user closes their laptop or loses signal. The app never gets to set status to 'offline'. We need the server to do it for us.

The .info/connected Node

Firebase exposes a special read-only boolean at .info/connected that is true when the client has a live connection and false when it does not.

import { getDatabase, ref, onValue } from 'firebase/database';

const db = getDatabase();
onValue(ref(db, '.info/connected'), (snap) => {
  console.log('Connected?', snap.val() === true);
});

onDisconnect Basics

onDisconnect registers an action that the server performs when the client disconnects. It is the key to reliable presence.

import { onDisconnect, set } from 'firebase/database';

const statusRef = ref(db, 'status/' + uid);
onDisconnect(statusRef).set({ state: 'offline' });

Order of Operations

The correct sequence is critical:

  • Wait until .info/connected is true
  • Register the onDisconnect action first
  • Only then set status to online

This guarantees the offline handler is armed before you go online.

A Complete Presence Setup

Combining the pieces gives a reliable presence system.

onValue(ref(db, '.info/connected'), (snap) => {
  if (snap.val() !== true) return;
  onDisconnect(statusRef).set({ state: 'offline', at: Date.now() })
    .then(() => set(statusRef, { state: 'online', at: Date.now() }));
});

Server Timestamps

Use serverTimestamp() instead of the client clock so 'last seen' times are consistent across devices with skewed clocks.

import { serverTimestamp } from 'firebase/database';

set(statusRef, { state: 'online', lastChanged: serverTimestamp() });

Multiple Devices

A user may be online on phone and laptop at once. Track presence per connection (a unique key per session) and treat the user as offline only when all connections drop.

import { push } from 'firebase/database';

const conRef = push(ref(db, 'status/' + uid + '/connections'));
onDisconnect(conRef).remove();

Cancelling onDisconnect

If the user logs out cleanly, cancel the pending onDisconnect action and set offline yourself, so stale handlers do not fire later.

import { onDisconnect } from 'firebase/database';

await onDisconnect(statusRef).cancel();
await set(statusRef, { state: 'offline' });

Displaying Presence

Other clients simply listen to the status node. A green dot appears when state is online and disappears when the server flips it to offline on disconnect.

onValue(ref(db, 'status/' + otherUid), (snap) => {
  const online = snap.val()?.state === 'online';
  toggleDot(online);
});

Best Practices

Keep presence reliable and cheap:

  • Store presence in a shallow, dedicated node
  • Use server timestamps for last-seen
  • Account for multiple connections
  • Always register onDisconnect before going online

Quick Check

Test your understanding of presence.

Recap

You can now build reliable online indicators.

  • Watch .info/connected for live connection state
  • Use onDisconnect so the server marks users offline
  • Register onDisconnect before going online
  • Use server timestamps and per-connection tracking
  • Cancel handlers on clean logout
Bezpłatny start

Ucz się Firebase Auth & Realtime Database Apps dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
11
Lekcje
44

Często zadawane pytania

Czy lekcja „Wykrywanie obecności i statusu online” jest bezpłatna?

Tak — pełny tekst „Wykrywanie obecności i statusu online” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Firebase Auth & Realtime Database Apps, przejdź na CoddyKit PRO. Kurs Firebase Auth & Realtime Database Apps zawiera 4 lekcji w sumie.

Co nauczysz się w „Wykrywanie obecności i statusu online”?

Twórz wskaźniki stanu online/offline działające na żywo, korzystając z mechanizmu obecności Realtime Database, procedur obsługi onDisconnect i specjalnego węzła .info/connected, aby niezawodnie odzwi… Ćwiczysz Firebase Auth & Realtime Database Apps z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Firebase Auth & Realtime Database Apps?

Nie wymagamy żadnego doświadczenia. Firebase Auth & Realtime Database Apps w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Wykrywanie obecności i statusu online”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Firebase Auth & Realtime Database Apps?

Tak. Każda lekcja Firebase Auth & Realtime Database Apps zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Włączanie przechowywania danych offline
  2. Obsługa rozłączeń sieciowych
  3. Strategie synchronizacji danych
  4. Wykrywanie obecności i statusu online
← Powrót do Firebase Auth & Realtime Database Apps