简体   繁体   English

在PWA中联机(WiFi打开)时后台同步代码无法自动工作

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

I am new to PWA and have been testing my PWA project using firebase console database. 我是PWA的新手,一直在使用firebase控制台数据库测试我的PWA项目。 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). 脱机时,我有代码将提交的数据提交到indexedDB当我将其提交到WiFi(在线)时保存。 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. 当没有找到WiFi时,它确实将数据保存在indexedDB ,但是当我打开WiFi时,它不会实时发布数据。 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. 当我在wifi开启(在线)时提交新的发布数据时,后台同步代码会实时发布indexedDB保存的数据和新发布的数据。 But i want my background sync codes to post automatically when WiFi is turned on(after offline). 但我希望我的后台同步代码在WiFi打开(离线后)后自动发布。

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. 请帮我解决这个问题,因为我陷入了困境。

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. 这是一个文档齐全的JS API,也得到了广泛的支持

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). 但是它无法区分工作的互联网连接还是仅区分连接(例如,没有实际互联网连接的WiFi热点)。

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. 因此,我建议您在navigator.onLine事件中进行一个伪造的API调用,以检查天气是否可以返回实际的互联网(也可以是一次简单的握手),一旦成功,您就可以继续进行您的常规API调用。

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... 希望这可以帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM