Service Worker: handle requests when offline to send them when online

ぐ巨炮叔叔 提交于 2019-12-23 04:56:31

问题


I have a chat web application and I want it to work offline. For this I use progressive web apps features (Service Workers) to use cache to get the shell app and the messages already loaded.

What I want to do is to be able to make a post message when I'm offline and let the service worker handle the connection issues (i.e.: keep the message somewhere till where are offline and as soon as we are online send the Post message).

I want to use Service Worker because I also want to send the message if the user as left the web app after posting a message with no connection.

What is the best API to use for this?

I saw the background sync API but it is not standard and it doesn't seem to be updated for almost 2 years.


If there is a way to do this in a manner that the client (the web app) is totally unaware of this mechanism it would be cool.

What I mean by that is I would like my app just do a fetch("/message", {method : "post", body : {content : "hey there"}) And then the Service Worker just intercept the fetch, if we are online then it just send the fetch, but if we are offline it "wait" for the connection to be up again and then send the post.


I wonder if there is an event listener, available in the service worker, that will be activated when the connection change from offline to online. This way I should be able to store the request in indexDB when offline and then send the post when online. I saw the navigator.onLine but it is not an event :(


回答1:


Based from this post, you may use a Service Worker in running the app in the background either via its push event handler (triggered via an incoming push message), or via its sync event handler (triggered by an automatic replay of a task that previously failed).

You may check the Offline Storage for Progressive Web Apps documentation for storing data offline:

  • For URL addressable resources, use the Cache API (part of service workers).
  • For all other data, use IndexedDB (with a promises wrapper).

You can cache static resources, composing your application shell (JS/CSS/HTML files) using the Cache API and fill in the offline page data from IndexedDB.



来源:https://stackoverflow.com/questions/46510547/service-worker-handle-requests-when-offline-to-send-them-when-online

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