I have added PWA to an angular application.
Below is the code inside the service worker, which listen to the sync event. Once service worker detects internet connection it triggers this sync event.
self.addEventListener('sync', function (event) {
console.log('syncing started.');
event.waitUntil(getAllrecordsAndPost());
});
In component:
Sync event registration:
navigator.serviceWorker.ready.then(function(swRegistration) {
return swRegistration.sync.register('myFirstSync');
});
This is working fine in the chrome at the desktop, but on the android chrome, background sync event is not working.
FYI: I am using latest chrome version (79).
EDIT:
After further investigation, I have found that sync event is getting triggered but inside that sync event a code for fetch is written, which is giving the error and that's why background sync is not working. below is the code which listens to sync event and hit the API.
(function () {
'use strict';
self.addEventListener('sync', function (event) {
event.waitUntil(postUrl());
});
function postUrl() {
let url = 'http://mytesturl.com/testAPI';
let data = {name:'test',age:10};
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: data
}).then((result)=>{
console.log('successful');
}).catch((x)=>{
console.log('error ' + x);
})
}
}());
In the console, i am getting error: error TypeError: Failed to fetch
Background sync is a new web API that lets you defer actions until the user has stable connectivity. This is useful for ensuring that whatever the user wants to send, is actually sent.
By doing this, apps will not sync in the background and will not send notifications until you open them. Disabling background sync can be a major benefit to battery life, but still allows phone calls to be received when your screen is off. This is a great alternative to Life Mode for many users.
Using a service worker, a Progressive Web App (PWA) can do work in the background, even when the user isn't using the app. Service workers used to be reserved for native apps, but they are now also available to PWAs, providing a better offline experience.
The Background Sync API allows web applications to defer server synchronization work to their service worker to handle at a later time, if the device is offline. Uses may include sending requests in the background if they couldn't be sent while the application was being used.
https://web.dev/periodic-background-sync/ indicates that background sync only works from a PWA "installed" and launch as a separate app (rather than as a tab in the browser) - can you clarify whether you attempted to launch it in these conditions?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With