Can Firestore for the web integrate with a service worker for background synchronization? For example, it seems a user must open the app for the synchronization to happen. It would be nice if background sync could happen through service worker so when user opens app everything is already synced.
2 Answers
firebaser here
There is no such functionality built into the Firestore JavaScript SDK right now. In fact: none of the Firestore SDKs perform such background synchronization.
If you think this would allow you to build better apps, then I'd file a feature request. But I'll admit that I doubt this is going to be a high priority for the near future, as I see many potential problems with it.
If you feel up to the challenge, you could also look at the Firestore JavaScript SDK source code and see how something like this might be added.
- 565,676
- 79
- 828
- 807
-
1Okay. The scenario I am thinking of is someone posting something while offline and closing app before connection is reestablished and the post will not happen until they open app again which potentially could be a long time therefore possibly important information is not relayed. I guess it won't hurt to file a feature request and I'll look at SDK. – paperjack Feb 11 '18 at 05:22
-
For sending/receiving notifications while the app is not foregrounded, you'll typically use a solution like Firebase Cloud Messaging. See https://firebase.google.com/docs/cloud-messaging/ – Frank van Puffelen Feb 11 '18 at 05:27
It might not have been possible at the time the question was asked but meanwhile with a chrome extension it is possible.
Since version 9 the Firebase Web SDK uses fetch instead of XMLHttpRequest. So it works inside a service worker.
Here is my working example for monitoring the Firestore database and updating the badge of a chrome extension in the background:
background.js:
var unsubscribe;
auth.onAuthStateChanged(function(user) {
if (user) {
const db = getFirestore(app);
let colReference = collection(db, "User", user.uid, "Reference");
unsubscribe = onSnapshot(colReference, function(querySnapshot) {
chrome.action.setBadgeText({text: querySnapshot.size.toString()});
});
} else {
unsubscribe();
}
});
See this answer on how to setup Firebase for a Chrome (Manifest v3) extension: https://stackoverflow.com/a/70815962/3243751
And this answer one how to use Firebase Auth for authenticating with the Firestore database: https://stackoverflow.com/a/70987391/3243751
- 733
- 6
- 16
-
Does onSnapshot continuously run I mean stay connected or gets disconnected after few second? In my case it disconnects after few seconds of inactivity. Any idea? – SkyRar Mar 09 '23 at 19:09
-
@SkyRar I just checked in my app and yes it seems the snapshot only works once. I don't know how to fix it. – FLUXparticle Mar 16 '23 at 17:24