Background Sync codes not working automatically when online(wifi on) in PWA

蓝咒 提交于 2019-12-13 03:58:00

问题


I am new to PWA and have been testing my PWA project using firebase console database. When offline, I have code to save my post data in indexedDB when i submit my post data to saved later when there is WiFi(online). It did save the data in indexedDB when no WiFi found, but when i turn on my WiFi, it doesn't post my data in realtime. When i submit new post data when wifi on(online), background sync codes do post saved data from indexedDB with newly post data in real time. But i want my background sync codes to post automatically when WiFi is turned on(after offline).

Here is my service worker code for background sync:

self.addEventListener('sync', function(event) {
  console.log('Background syncing...', event);
  if (event.tag === 'sync-new-posts') {
    console.log('Syncing new Posts...');
    event.waitUntil(
      readAllData('sync-posts') // function to read all saved data which had been saved when offline
        .then(function(data) {
          for (var dt of data) {
            fetch('xxx some firebase post url xxx', { // fetching for sending saved data to firebase database
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
              },
              body: JSON.stringify({
                id: dt.id,
                title: dt.title,
                content: dt.content
              })
            })
              .then(function(res) {
                console.log('Sent data', res);
                if (res.ok) {
                    res.json()
                        .then(function (resData) {
                            deleteItemFromData('sync-posts', resData .id); // function for deleting saved post data from indexedDB as we donot need after realtime post is saved when online.
                        });
                }
              })
              .catch(function(err) {
                console.log('Error while sending data', err);
              });
          }
        })
    );
  }
});

I don't know what's go wrong. If anyone need more of my codes of my posting codes or serviceworker codes for more clarity, please do ask. Please help me with this as i am stuck in this.


回答1:


What you can do is check weather the your app is online again or not using Online and offline events. This is a well documented JS API and is widely supported as well.

window.addEventListener('load', function() {
  function updateOnlineStatus(event) {
    if (navigator.onLine) {
      // handle online status
      // re-try api calls
      console.log('device is now online');
    } else {
      // handle offline status
      console.log('device is now offline');
    }
  }

  window.addEventListener('online', updateOnlineStatus);
  window.addEventListener('offline', updateOnlineStatus);
});                        

NOTE: It can only tell if the device is connected. BUT it CANNOT distinguish between a working internet connection or just a connection (Eg. WiFi hotspot without actual Internet connectivity).

So, I'd suggest you to do a fake API call in the navigator.onLine event just to check weather the actual internet is back or not (it can be a simple handshake as well) and once the is successful you can go on doing your regular API calls.




回答2:


Check if update on reload is switched off and that you are fully offline. I had the same issue then it randomly started working when update on reload was turned off. I think its because it reinstalls the service worker each time you refresh the page so you're not in the state where the service worker is listening for the sync. Thats my theory to it anyway. Hope this helps...



来源:https://stackoverflow.com/questions/50405573/background-sync-codes-not-working-automatically-when-onlinewifi-on-in-pwa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!