Using the Web Locks API to Ensure a Single Active Browser Tab
Use navigator.locks.request with a unique lock name to enforce single active tab; the browser handles queuing, stale data, and race conditions.
Implement navigator.locks.request with a unique lock name to enforce single active tab.
Summary
The article tackles the problem of ensuring only one browser tab remains active while others are locked, a requirement that arises in single‑page applications. It first surveys naive solutions using localStorage and BroadcastChannel, noting their shortcomings with stale data and race conditions. The author then introduces the Web Locks API, which lets a tab acquire a named lock (e.g., dev:app) and automatically releases it when the tab closes. A React example shows navigator.locks.request acquiring the lock and setting an active state, while the UI renders a lock message for other tabs. Edge cases such as the next active tab, stale locks, and race conditions are all handled by the browser, eliminating the need for manual bookkeeping. The conclusion stresses that leveraging built‑in browser APIs can simplify complex coordination logic and improve reliability.
Key changes
- localStorage and BroadcastChannel approaches suffer from stale data and race conditions.
- Web Locks API provides built‑in tab locking with queuing.
- Lock name dev:app identifies the shared resource.
- navigator.locks.request acquires the lock and sets active state.
- Browser automatically releases lock on tab close, eliminating stale locks.
- Race conditions are handled by the browser’s lock queue.
- UI updates based on lock status, rendering lock message for non‑active tabs.