Web Locks API
The Web Locks API allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, then release it. While held, no other script executing in the same origin can acquire the same lock, which allows a web app running in multiple tabs or workers to coordinate work and the use of resources.
A lock is an abstract concept representing some potentially shared resource, identified by a name chosen by the web app.
The API is used as follows:
The lock is requested.
Work is done while holding the lock in an asynchronous task.
The lock is automatically released when the task completes.
navigator.locks.request("my_resource", async (lock) => {
// The lock has been acquired.
await do_something();
await do_something_else();
// Now the lock will be released.
});
While a lock is held, requests for the same lock from this execution context, or from other tabs/workers, will be queued. The first queued request will be granted only when the lock is released.
Locks are scoped to origins; the locks acquired by a tab from https://example.com have no effect on the locks acquired by a tab from https://example.org:8080 as they are separate origins.
The main entry point is navigator.locks.request() which requests a lock. It takes a lock name, an optional set of options, and a callback. The callback is invoked when the lock is granted. The lock is automatically released when the callback returns, so usually the callback is an async function, which causes the lock to be released only when the async function has completely finished.
The request() method itself returns a promise which resolves once the lock has been released; within an async function, a script can await the call to make the asynchronous code flow linearly.
await do_something_without_lock();
// Request the lock.
await navigator.locks.request("my_resource", async (lock) => {
// The lock has been acquired.
await do_something_with_lock();
await do_something_else_with_lock();
// Now the lock will be released.
});
// The lock has been released.
await do_something_else_without_lock();