Web applications have been able to execute code, make network requests, and interact with the user through a browser tab or standalone browser window. This has allowed users to directly see that a web application is executing code, and generally doing useful things, on their behalf.
Following the introduction of the Push API and Background Synchronization, this assumption no longer holds: web applications are now able to both trigger and schedule execution of code in the background, outside of the user’s control. This brings web application functionality closer to native applications or browser extensions, both of which are able to perform extensive Background Operations.
In order to protect the user, Chrome has historically required developers to display a notification in response to a message. Firefox grants developers a budget based on the level of engagement a user has with a website, which is a model that Chrome, with the release of Chrome 52, has moved to as well.
In both cases, it's an unknown to the developer whether they have to show a notification. This eliminates a lot of potential use-cases for the Push API. The Budget API aims to standardize this concept of budget in a way that provides value for developers, while not locking user agents into any particular implementation.
Today the Budget API focuses on the Push API, but we chose to generalize the concept in order to (1) be able to provide both immediate and expected values, enabling developers to do near-term resource planning, (2) be able to extend existing APIs such as Background Sync both to alleviate the restrictions and to enable developers to request more retries, and (3) enable future resource consuming APIs such as a Job Scheduler to use the same mechanism.
This API solely focuses on resource consuming APIs.
self.addEventListener('push', event => {
// Execute the application-specific logic depending on the contents of the
// received push message, for example by storing the received update.
event.waitUntil(async () => {
const reserved = await navigator.budget.reserve('silent-push');
if (reserved) {
return; // No need to show a notification.
}
// Not enough budget is available, must show a notification.
return registration.showNotification(...);
});
});
async function getPreciseTimersAvailableAt(time) {
const [ cost, budget ] = await Promise.all([
navigator.budget.getCost('precise-timer'),
navigator.budget.getBudget()
]);
for (const state of budget) {
if (state.time <= time) {
continue;
}
// The |state| occurs after |time|, so return the budget.
return state.budgetAt / cost;
}
// No budget after |time| is known, so we can't guarantee anything.
return 0;
}