微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Lighthouse PWA 审计失败“未注册控制页面和 start_url 的服务工作者”

如何解决Lighthouse PWA 审计失败“未注册控制页面和 start_url 的服务工作者”

我在灯塔审计中遇到了上述故障。浏览了 SO 和 here 它“应该”工作。

控制台中没有错误

这是清单:-

{
"short_name": "brotkrumen","name": "brotkrumen Web App","description": "Native Background Geolocation POC","icons": [
{
  "src": "gingerbreadhouse.png","sizes": "48x48 128x128 144x144 192x192 512x512","type": "image/png"
}
],"start_url": "/TravelManager.html","background_color": "#00ccdd","theme_color": "#00ccdd","display": "fullscreen"
 }

这是ServiceWorker代码:-

'use strict';
 /* identification division.
  * program-id.    echo.
  * author.        Richard Maher.
  */

var   doryRegister  = [];            // Meet someone new every day.
const INTRO         = "GrussGott";   // Tell clients we're new.
const FLEET_MANAGER = "/Fleet/Move"; // Starship control.
const CACHE_NAME    = "brotkrumenV1.0"
    
self.addEventListener('install',function (e) {
    e.waitUntil(
        caches.open(CACHE_NAME).then(function (cache) {
            return cache.addAll([
                '/TravelManager.html','/hg.png','/gingerbreadhouse.png','/striped-witch-hat.png','/brotkrumen.css','/echo.js','/registerserviceworker.js','/brotkrumen.json','/TravelManagerpolyfill.js','/HandleMap.js'
            ]).then(() => self.skipwaiting());
        })
    );
});

self.addEventListener('activate',function(e) 
{
    e.waitUntil(
        caches.keys().then((keyList) => {
            return Promise.all(keyList.map((key) => {
                if (key !== CACHE_NAME) {
                    console.log('Removing cache',key);
                    return caches.delete(key);
                }
            }));
        })
    );

    e.waitUntil(self.clients.claim());
});

self.addEventListener('fetch',function (e) {

    console.log(e.request.url);
    if (e.request.url.startsWith(self.location.origin)) {
        e.respondWith(

            caches.match(e.request).then(function (response) {
                console.log("Request " + e.request.url);
                if (response) {
                    console.log("Response " + response.url);
                    if (e.request.cache === 'only-if-cached') {
                        e.request.mode = 'same-origin'
                    }
                } else
                    console.log("No MATCH");

                return response || fetch(e.request);

            })

        );
    }
    return fetch(e.request);
});

注册服务工作者代码:-

'use strict';
/* identification division.
 * program-id.    RegisterServiceWorker.
 * author.        Richard Maher.
 * version.       1.0
 */

function registerServiceWorker()
{   
// Make sure SW is there
navigator.serviceWorker.register('echo.js',{scope: './'})
    .then(reg => {
            window.addEventListener("unload",unsubscribeTravelManager);
            console.log('SW Registered');
        })
    .catch(err => {
        console.log('SW Registration Failed with ' + err);
        reportError({header:"Could not register ServiceWorker",message:err});
        return;
    });
  
// Register for Background Geolocation tracking. Take default for accuracy,max age.    
navigator.serviceWorker.ready
    .then(reg => {
        reg.travelManager.subscribe({
                            minSilence:     5,// Car trip value. Collapse GPS.
                            maxSilence:   600,// Sanity check. Squelch off.
                            minProgress:   50,// Indoor accuracy an issue.
                            maxSnail:      55,// Brisk walk.
                            dropDodgy:   true  // Avoid wireless Pong.
                            })
            .then(subscription => {travelSubscription = subscription},locFail)
            .catch(err => {
                    console.log('Travel Manager Subscription Failed with ' + err);
                    reportError({header:"Could not subscribe to Travel Manager",message:err});
            });
    });
}

function unsubscribeTravelManager(e)
{   
// Tidy up
const CANCEL   = true;
var   shutdown = Promise.resolve(false);

if (travelSubscription) 
    shutdown = travelSubscription.unsubscribe(CANCEL);
    
shutdown
    .then(success => {
            console.log("Unsubscribed from TravelManager = " + success);
            navigator.serviceWorker.ready
                .then(reg => {
                        reg.unregister()
                        .then(success => {console.log('SW Unregistered = ' + success)})         
                        })          
        })
    .catch(err => console.log("Couldn't unregister SW " + err))
 }

解决方法

替换

"start_url": "/TravelManager.html"

"start_url": "."
,

飞行员错误:-(

在页面卸载事件中,当我取消订阅 TravelManager 时,我也取消了 ServiceWorker 的注册,这有点违背了目的。我的错。

,

我认为问题出在您的服务人员身上。我没有找到您在特定 URL 上注册 Service Worker 的任何代码。

const serviceWorkerUrl = '/sw.js';

if ('serviceWorker' in navigator) {
  window.addEventListener('load',function() {
    navigator.serviceWorker.register(serviceWorkerUrl).then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ',registration.scope);
    },function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ',err);
    });
  });
}

您应该在为 installactivatefetch 添加事件侦听器之前注册您的 Service Worker。如果您想了解更多信息,请关注此 documentation

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。