vndpal
vndpal

Reputation: 757

Background sync in Service Worker is not working in chrome on android

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

Upvotes: 6

Views: 3918

Answers (2)

vndpal
vndpal

Reputation: 757

Background sync of the service worker gets triggered as soon as it has detected the internet connection.

Therefore, anything inside the sync event will also execute (post requests) immediately. Irrespective of stability of the internet connection, So to avoid this I have added a timeout of 3 seconds. now its working as expected.

Sync event listener inside service worker:

 self.addEventListener('sync', function (event) {
    event.waitUntil(setTimeout(function(){getAllrecordsAndPost()},3000));
    });

Upvotes: 2

dontcallmedom
dontcallmedom

Reputation: 2480

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?

Upvotes: 3

Related Questions