0

My website have the intention to in the background (when tab is not in focus) constantly check, with an interval of maybe one minute, with a server by making web requests to that server, and get a response back, if the message sends back a message, i.e not an error, the website should send a push notification / desktop notification.

I tried and succeeded with registering a service worker that was caching some background files, but I didn't know if this would be to any help as I didn't find any information about how to proceed from installing the service and creating a function that constantly checks information with a server and then display a message.

How can I resolve this?

Snakehater
  • 145
  • 1
  • 9
  • If you only want to have notifications while the tab is still open (but not focused), I don't think you need a service worker. – Bergi Aug 09 '20 at 20:42
  • I tried with just using a loop with requestAnimationFrame and set timeout so that it loops and it stops looping when tab is out of focus. – Snakehater Aug 09 '20 at 20:57
  • No, don't do that, just use [`visibilitychange` events](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API) for detecting when your tab looses focus. – Bergi Aug 09 '20 at 21:00
  • If your page is still open (e.g. in another tab) you don't need the service workers. Otherwise, if your website is closed, you need to use Service workers + Web Push API... You can't use a cron job when the website is closed. – collimarco Aug 09 '20 at 22:26
  • But how do I use visibility change to constantly check in the background? Doesn't visibility change fire only once? I need something that can check each minute with a server. @Bergi. – Snakehater Aug 10 '20 at 07:32
  • A crib job seems interesting @collimarco. How can I implement something like that? I don't need the website to check with my server when closed. – Snakehater Aug 10 '20 at 07:33
  • @Snakehater To check each minute, you'd use `setInterval(checkForUpdates, 36e5)` or `setTimeout`s, yes. I guess I misunderstood your comment, I thought you were using `requestAnimationFrame` so that you could detect when the tab is out of focus. – Bergi Aug 10 '20 at 09:25
  • @Bergi does this solution work when tab and window is not in focus? – Snakehater Aug 10 '20 at 15:07
  • @Snakehater I think it does, but you'll have to test. Browsers *do* throttle intervals on background tabs, but I'd assume a 60s interval should run fine. – Bergi Aug 10 '20 at 15:43
  • @Bergi yes, it did work almost fine, but fine enough for what I am doing, you should post it as an answer. – Snakehater Aug 11 '20 at 13:50

0 Answers0