Service worker: Fetch event listener only works after page reload

你。 提交于 2019-11-29 22:14:45

问题


I have added a service worker to my page with the code below. It works well once the page has been reloaded and the worker already installed. But does not seem to catch any fetch events before the page is reloaded after I have seen the 'SW INSTALL' log.

app.js

navigator.serviceWorker.register('/worker.js').then((registration) =>
{
    console.log('ServiceWorker registration successful with scope: ', 
registration.scope);
}, (err) =>
{
    console.log('ServiceWorker registration failed: ', err);
});

worker.js

self.addEventListener('install', function (event)
 {
    console.log("SW INSTALL");
 });

self.addEventListener('fetch', function (event)
{
    console.log("FETCHING", event);
    event.respondWith(
            caches.match(event.request)
                    .then(function (response, err)
                            {
                                // Cache hit - return response
                                if (response)
                                {
                                    console.log("FOUND", response, err);
                                    return response;
                                }
                                console.log("MISSED", event.request.mode);
                                return fetch(event.request)
                            }
                    )
    );
});

回答1:


Solution: Adding the following to worker.js;

self.addEventListener('activate', function (event)
{
    event.waitUntil(self.clients.claim());
});

Service workers don’t immediately “claim” the sessions that load them, meaning that until your user refreshes the page your service worker will be inactive.

The reason for this is consistency, given that you might otherwise end up with half of your webpage’s assets cached and half uncached if a service worker were to come alive partway through your webpage’s initialization. If you don’t need this safeguard, you can call clients.claim and force your service worker to begin receiving events

Read more @ service-workers



来源:https://stackoverflow.com/questions/45007878/service-worker-fetch-event-listener-only-works-after-page-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!