简体   繁体   中英

How does vue PWA use the precache? I still get "Page does not work offline"

I have a vue application that I updated to have PWA capability. It uses the firebase messaging service that has overridden the service worker with its own firebase-messaging-sw.js file. The service worker is registered, active and working, I have added the pwa in the vue.config.js file so that it generates the manifest.json. When you build the production version of the app the following code gets added to the top of the service worker.

importScripts("precache-manifest.7b51ac9589a6dc8041a85d8f1792defa.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

From what I see the percache works fine.

Should this be enough to get the site to work in offline mode?

Do I need to add some cache management myself?

What am I missing because I still get the "Page does not work offline" error message in Chrome's dev tools under the App manifest tab.

Looks like Google also picked up on the quick hack and the warning has returned.

So since of Chrome93 (AUG-2021) the quick hack, will not work anymore :

self.addEventListener('fetch', function(event) {})

Solution working "for now" (since we never know what requirements Google will add later on)

I've found a nice article which provides with a few solutions, the first one the author provides is Network-Falling-Back-To-Cache strategy:

your service worker will first try to retrieve the resource from your server. Then when it can't do that — because for example, you're offline — retrieve it from the cache (if it exists there).

   self.addEventListener('fetch', function(event) {
   event.respondWith(async function() {
      try{
        var res = await fetch(event.request);
        var cache = await caches.open('cache');
        cache.put(event.request.url, res.clone());
        return res;
      }
      catch(error){
        return caches.match(event.request);
       }
     }());
 });

You can find all the information and alternative solutions in the article:

https://javascript.plainenglish.io/your-pwa-is-going-to-break-in-august-2021-34982f329f40

I hope this will help futur visitors.

Additional side note:

using the above code you might encounter the following error:

service-worker.js:40 Uncaught (in promise) TypeError: Failed to execute 'put' on 'Cache': Request scheme 'chrome-extension' is unsupported

This error is caused by chrome extentions like Augury or Vue dev-tools. Switching both off will cause the error to disappear.

You need to add this line in the serviceworker. It fools the browser into thinking that the page will work offline:

self.addEventListener('fetch', function(event) {}) // add this to fool it into thinking its offline ready

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM