6

I built a PWA that fetches data from firestore. I want to run some checks on that data every couple of hours which is why I want to use a service worker for that.

This is a snippet from my working code:

billsCollection.orderBy('dayOfMonth', 'asc').onSnapshot(querySnapshot => {
  let billsArray = [];
  querySnapshot.forEach(doc => {
    let bill = doc.data();
    bill.id = doc.id;
    billsArray.push(bill);
  });
  store.commit('setBills', billsArray);
});

If I try to run .onSnapshot in my service worker I get the message that xmlhttprequest is not known or similar.

It seems like 'firebase/app' and 'firebase/firestore' use the old xmlhttprequest to communicate with firebase/firestore. Service Workers only support the newer fetch api. Has anybody successfully fetched data from firebase/firestore before using the new fetch api?

I would like to periodically fetch data from firebase using a service worker.

If that does not work, is it possible to check your data with a Cloud Firestore function? I am not sure since it would need a time event trigger or similar.

Thanks everybody for your ideas, Johannes

Edit:

As Scarygami pointed out I can solve that problem by using a cron service that triggers a firestore function. This works. Nevertheless, I am still looking for a way to fetch data from firestore with a service worker directly. Then I would not need a 3rd party cron service or cloud functions and the specific token of the device I want to send a message to. It would simply fetch data, check data, show notification if needed.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
JDr
  • 127
  • 9
  • Wouldn't a web worker (which supports XMLHttpRequest) be better suited for this use case? As for cloud functions, you can use a 3rd cron service, like cron-job.org, to trigger https functions – Scarygami Aug 25 '18 at 01:02
  • I did some research but I can't find a simple answer. Do web workers stay alive when the user closes the application/page/browser? If yes then I can use a simple web worker instead. I will look into cron-job.org. Thank you – JDr Aug 25 '18 at 01:31
  • Looks like firestore accepts http requests as a trigger. That is perfect and I can use cron-job to do the request. Thank you for pointing me in that direction. – JDr Aug 25 '18 at 01:58
  • It might not have been possible at the time the question was asked but meanwhile it is possible. See my other answer here: https://stackoverflow.com/a/71014462/3243751 – FLUXparticle Feb 07 '22 at 13:58

0 Answers0