javascriptprogressive-web-appsservice-workerfacebook-pixel

PWA Service Worker - Failed to fetch - Issue with Facebook Pixel


I have the following PWA Service Worker (serviceWorker.js):

self.addEventListener("fetch", fetchEvent => {
  fetchEvent.respondWith(
    caches.match(fetchEvent.request).then(res => {
      return res || fetch(fetchEvent.request)
    })
  )
})

I don't want anything to load when offline, because it's a fully dynamic webpage, so offline it's unusable. So that's why I found that maybe this code is enough for the Service Worker, and I don't need any cached files. (Maybe that was a mistake?) And actually it's working fine, at least when I open my webpage, Chrome pops up the message to install the application for my webpage - and it's also working fine.

But today I have realized that in the Console there are some errors regarding it:

The FetchEvent for "https://connect.facebook.net/en_US/fbevents.js" resulted in a network error response: the promise was rejected.

Uncaught (in promise) TypeError: Failed to fetch at serviceWorker.js:4:21

And marks this part in the serviceWorker.js: fetch(fetchEvent.request), and says: Failed to fetch.

GET https://connect.facebook.net/en_US/fbevents.js net::ERR_FAILED

Also when I wanted to make some changes in my Facebook Pixel, it said, it can't find the Pixel for my website. However it's there. And the only modification was to add the PWA-related codes.

And I also realized that since that day the visits of my webpage shown in Google Analytics started to drop down dramatically. Not 0 now, but I think in 1-2 days it will be 0.

What is the issue here with the Service Worker? How can I fix it? And what is the connection between this issue and my Facebook Pixel (and Google Analytics)?

Of course I tried to search for answers, but I could not find the solution for that particular issue.

Please help me fix this issue. Hopefully the root cause is the same, so one fix would solve all.

Thank you in advance.


Solution

  • I found the solution - I post it here, so maybe somebody will face this issue as well, and I want to help with the solution.

    So it turned out, I have to provide an offline fallback page.

    I found this article, I followed the steps, created the offline.html file, modified the serviceWorker.js file, and the issue is gone, Facebook Pixel is working fine again: https://web.dev/offline-fallback-page/