When a web application is opened in several tabs at once, each tab typically runs JavaScript independently. If all of them attempt to synchronize data, update caches, or submit the same job simultaneously, the result can be duplicate requests, excessive quota usage, or local data being overwritten. Web Locks API provides a coordination mechanism so that tabs and workers on the same origin can take turns accessing shared tasks or resources.
What Is Web Locks API?
Web Locks API is a browser interface for requesting and holding a named lock while an asynchronous task runs. The lock name is defined by the application, such as sync-database or refresh-session. When one context holds an exclusive lock, subsequent requests with the same name will wait until the lock is released.
Locks are managed by the browser and apply to the same origin—the combination of scheme, host, and port. Therefore, tabs from https://example.com can coordinate with other tabs on that origin, but not with subdomains or different ports. This API is also available to Web Workers and requires a secure context, typically HTTPS pages.
How It Works: Request, Execute, Release
The main entry point is navigator.locks.request(). The application requests a lock with a specific name, runs work inside a callback, and the browser releases the lock when the callback completes. If the callback is asynchronous, the lock remains held until the returned Promise settles or rejects.
async function syncData() {
// Replace with your application's synchronization process.
await fetch("/api/sync", { method: "POST" });
}
async function syncOncePerOrigin() {
if (!navigator.locks) {
// Provide a fallback strategy for unsupported browsers.
await syncData();
return;
}
await navigator.locks.request("nazuaf-data-sync", async () => {
await syncData();
});
}
If multiple tabs call syncOncePerOrigin() simultaneously, only one callback with the exclusive lock named nazuaf-data-sync runs at a time. Subsequent requests will wait their turn. This example is illustrative only; endpoints and fallback policies need to be adapted for real applications.
Most Useful Use Cases
- Preventing repeated synchronization. Multiple tabs may attempt to update data from the server. Locks help limit this process to one active job per origin.
- Electing a coordinator tab. Applications can use a simple leader election pattern: the tab that successfully acquires the lock runs polling or background tasks, while other tabs wait or perform alternative work.
- Protecting local data updates. If multiple tabs read and write the same records through IndexedDB, locks can help organize application-level operation ordering.
- Reducing duplicate work. Cache generation, session checks, or local queue processing can be run by one context at a time.
Locks do not automatically make database operations transactional. If the server receives duplicate requests from different devices, the application still requires server validation, database transactions, or idempotency keys as needed.
Exclusive and Shared Locks
The default mode is exclusive: one lock holder per name at a time. shared mode allows multiple readers to hold the same lock simultaneously, as long as no exclusive lock blocks them. This pattern is useful when multiple tabs may read a resource, but updates need to wait until reading completes.
// Multiple tabs can read simultaneously.
await navigator.locks.request(
"report-data",
{ mode: "shared" },
async () => {
await readReport();
}
);
// Write operations request exclusive access.
await navigator.locks.request("report-data", async () => {
await updateReport();
});
Ensure all parts of the application use consistent lock names and access rules. Locks only protect code that explicitly requests the same lock; other code that ignores it can still modify data.
Handling Locks That Cannot Be Acquired Immediately
The ifAvailable: true option allows the application to skip work if the lock is currently held by another party, rather than entering a queue. The callback receives null when the lock is unavailable.
await navigator.locks.request(
"background-refresh",
{ ifAvailable: true },
async (lock) => {
if (!lock) return; // Another tab is handling refresh.
await refreshData();
}
);
This approach suits background tasks that can be deferred, such as periodic refreshes. For operations that must complete, do not use this option without a clear queuing or retry strategy.
Risks and Safe Implementation Practices
- Keep lock duration short. Do not hold locks during unnecessary work. While the callback has not completed, other requesters with the same name must wait.
- Avoid deadlocks. If multiple locks are needed, request them in a consistent order and avoid mutual waiting through callback chains. Deadlocks on locks can stall application work.
- Design for failure. Use
try/finallyfor resource cleanup, handle Promise rejections, and ensure the UI continues to provide feedback when requests are waiting. - Prepare fallbacks. Check for
navigator.locksavailability and provide appropriate strategies. Simple fallbacks do not guarantee cross-tab coordination; where consistency matters, consider additional mechanisms and server validation. - Test with multiple tabs and workers. Simulate slow tabs, network failures, closed tabs, and stacked lock requests. For diagnostics,
navigator.locks.query()can display a snapshot of held and requested locks, if supported.
Conclusion
Web Locks API helps web applications coordinate work that might otherwise run in duplicate when multiple tabs or workers are active. With consistent lock names, short callbacks, failure handling, and proper fallbacks, applications can reduce duplicate synchronization and local update conflicts. However, browser locks are not a substitute for server-side consistency controls: transactions, authorization, and protection against repeated requests must still be designed at the appropriate layer.
Technical references: Web Locks API documentation on MDN and Web Locks API specification.

Komentar (0)
Belum ada komentar. Jadilah yang pertama berkomentar.