Getting started with Periodic Background Sync API in Chrome
When a progressive web app or service worker-backed page is launched, periodic background synchronisation enables you to display new content. When the app or page is not being used, it accomplishes this by downloading data in the background. This stops the app's content from updating while being viewed after it launches. Even better, the app stops refreshing before displaying a content spinner.
Web apps must use alternative methods to download data without regular background syncing. A typical illustration is waking a service worker up with a push notification. The user is interrupted by a message such as "new data available.". The updating of the data is merely a byproduct. You can still use push notifications for crucial updates like significant breaking news.
Background sync and periodic background synchronisation need to be clarified. Even though their names are similar, they have distinct functions. Background synchronisation is most frequently used, among other things, to resend data to a server after a failed request while periodic sync ensures that whenever user comes back to a tab, they find latest data and don't have to start their session with a refresh, like you expect today from your mail inbox.
Requirements
Your site must meet a few requirements before periodic background syncs are enabled to prevent websites from abusing this. Additionally to these requirements, check to see if your browser is supported.
Web Browser Support
Only Chromium-based browsers currently support the periodic sync API. This is Chrome v80, Edge v80, Android Browser v81, and Chrome for Android v81, as this article was written. On caniuse.com, you can view the most recent update.
The Chrome Platform Status indicates that neither Firefox nor Safari has made any public indications about this API. This might alter, though, if it proves helpful for browsers built on the Chromium platform.
Progressive Web App
Your website must be a Progressive Web App and installed to sign up for recurring background synchronisation. Enjoy the benefits of a Progressive Web App by installing it for recurring background synchronisation and enhanced user experience.
Internet access
Only previously used internet connections allow for the sync to take place. This security measure stops network requests from being sent to untrusted networks.
Ensure secure sync by restricting network requests to previously used and trusted internet connections, providing an additional layer of security.
Site engagement score
Adding an API that enables JavaScript to be executed without user interaction raises concerns about security and extensive data usage. This is where Chromium's site engagement score, which aims to stop the abuse of this API, comes into play.
The site engagement score, which ranges from 0 to 100, is determined by how frequently a user interacts with a website. In addition, whether the application is installed is taken into account. On the Chromium website, you can find more information about this. This implies that the frequency of the potential syncs depends on this score for the periodic background sync.
When can you use it?
Each browser has its usage policies. As a result of the mentioned requirements, Chrome imposes the following constraints on recurring background sync:
- A particular user engagement score.
- Presence of a previously used network.a network that has been used before.
Developers have no control over when synchronisations happen. The frequency of synchronisation will depend on how frequently the app is used. (Note that, at the moment, platform-specific apps do not do this.) It also takes into the device's power and connectivity state.
When should you use it?
You can request data when your service worker awakens to handle a periodic sync event, but you are not obligated to do so. Considering the network and storage conditions, you should download varying amounts of data in response to the event.
Permissions
Make a periodic background-sync query using the Permissions API after the service worker has been installed. Either a window or a service worker context can be used for this.
navigator.permissions.query({ name: 'periodic-background-sync' }) .then((permissionStatus) => { if (permissionStatus.state === 'granted') { // Periodic background sync is granted, you can register a sync event self.registration.periodicSync.register('syncEvent', { // Set the minimum interval for the sync event minInterval: 24 * 60 * 60 * 1000, }); } }) .catch((error) => { console.error('Error checking permission:', error); });
Registering a periodic sync
Periodic background sync necessitates a service worker, as was already mentioned. Using ServiceWorkerRegistration.periodicSync, get a PeriodicSyncManager and use register(). A tag and a minimal synchronisation interval (minInterval) are needed for registration. Multiple syncs can be registered because the tag identifies the registered sync. The tag name in the example below is "content-sync," and the mininterval value is one day.
self.registration.periodicSync.register('myPeriodicSync', { minInterval: 24 * 60 * 60 * 1000, // Minimum interval of 24 hours }) .then(() => { console.log('Periodic sync registered'); }) .catch((error) => { console.error('Error registering periodic sync:', error); });
Verifying a registration
To get an array of registration tags, use periodicSync.getTags(). To avoid updating again, the example below uses tag names to verify that cache updating is active.
const registration = await navigator.serviceWorker.ready; if ('periodicSync' in registration) { const tags = await registration.periodicSync.getTags(); // Only update content if sync isn't set up. if (!tags.includes('content-sync')) { updateContentOnPageLoad(); } else { // If periodic background sync isn't supported, always update. updateContentOnPageLoad(); }
To allow users to turn particular types of updates on or off, you can also use getTags() to display a list of active registrations on your web app's settings page.
In response to a periodic background sync event
You should add a periodicSync event handler to your service worker to respond to periodic background sync events. A tag parameter with the same value as the one used for registration will be present in the event object passed to it. For instance, event.tag will be "content-sync" if a recurring background sync was registered with that name.
self.addEventListener('periodicsync', (event) => { if (event.tag === 'syncEvent') { event.waitUntil(doSync()); } }); function doSync() { // Perform the necessary background sync tasks // This function will be called whenever a periodic sync event occurs // You can add your own custom logic here // Example: Fetch data from a remote server return fetch('https://api.example.com/data') .then((response) => response.json()) .then((data) => { // Process the fetched data console.log('Periodic sync completed:', data); }) .catch((error) => { console.error('Periodic sync error:', error); }); }
Unregistering a sync
Call periodicSync to terminate a registered sync. Give the name of the sync you want to unregister to unregister().
navigator.serviceWorker.ready .then((registration) => { return registration.periodicSync.unregister('syncEvent'); }) .then(() => { console.log('Periodic sync unregistered'); }) .catch((error) => { console.error('Error unregistering periodic sync:', error); });
Debugging
Chrome 81 and later support periodic background sync debugging. You must do this for debugging and periodic background syncs because they only function when the web application is installed. On the right of the URL bar in Google Chrome, there is a tiny + sign. This only appears if your PWA can be installed and you are not browsing in incognito mode (for help troubleshooting this, go to DevTools > Lighthouse). Installing your PWA is necessary to troubleshoot periodic syncs.
Initiate periodic syncs
After installation, press F12 to launch the DevTools. You can start a recurring sync by going to Application > Service Worker. To simulate a sync, enter the tag name for your sync (in this case, news) and press the Periodic Sync button.
Record activity
Periodic Background Sync is located in the Application tab's left menu. If you click the record button, chrome will record all local periodic sync events for a maximum of three days.
Event simulation
Even though it can be useful to record background activity, there may be times when you want to test your periodicsync handler right away rather than waiting for an event to fire on schedule. This can be done in Chrome DevTools' Application panel's Service Workers section. You can tag and trigger the event as many times as you would like using the PeriodicSync field.
Interfaces
Here is a summary of the Periodic Background Sync API's interfaces.
PeriodicSyncEvent: passed by the browser at a predetermined time to the
ServiceWorkerGlobalScope.onperiodicsync event handler.
PeriodicSyncManager: periodic syncs are registered and unregistered, and tags are provided for registered syncs. Get an instance of this class from the ServiceWorkerRegistration.periodicSync' property.
ServiceWorkerGlobalScope.onperiodicsync: creates a handler that will receive periodicsyncevents.
ServiceWorkerRegistration.periodicSync: provides a reference to the PeriodicSyncManager as a response.
In a Nutshell
Chrome's Periodic Background Sync API enables progressive web apps to synchronise and periodically display new content in the background. By meeting the requirements of being a Progressive Web App, utilising previously used internet connections, and ensuring site engagement scores, developers can leverage this API for enhanced user experiences. With the ability to register sync events, handle periodic syncs in the service worker, and debug the functionality through Chrome DevTools, this API offers a powerful tool for keeping web apps up-to-date and engaging for users.
Overall, the Periodic Background Sync API facilitates the seamless delivery of fresh content and updates in progressive web apps, enhancing user engagement and satisfaction. By leveraging this API and adhering to its requirements, developers can create dynamic and responsive web experiences that offer timely and relevant information to users, even when the app is not in use.
How much is a great User Experience worth to you?
Browsee helps you understand your user's behaviour on your site. It's the next best thing to talking to them.