ServiceWorker registration.update()看不到更新

时间:2018-07-27 14:46:54

标签: javascript service-worker

我是ServiceWorkers的新手,正在尝试弄清楚如何在create-react-app中手动检查应用程序更新。我们创建了一个自定义类来替代[{基于] registerServiceWorker.js文件。我们有一个测试按钮,它将运行registration.update()

此类被添加到mobx提供程序中,并注入到home组件中,该按钮是我用来手动运行updateServiceWorker()方法的按钮。

在已打开的选项卡上-部署后-单击运行updateServiceWorker的按钮。我在该函数中看到了三个控制台日志,但是handleOnUpdateFound函数没有运行。然后,如果我单击Chrome>开发工具>应用程序> Service Workers中的Update链接,则会执行handleOnUpdateFound回调,并且我们观察到布尔值的消息将按预期显示。

与我们在本课程中所做的更新和Chrome正在做什么有什么不同?

这是课程:

import { observable, action } from 'mobx';

export interface IAppStateService {
    isLocalhost: boolean;
    registerServiceWorker();
    unregisterServiceWorker();
    updateServiceWorker();
}

export class AppStateService implements IAppStateService {
    @observable installingUpdate: boolean = false;
    @observable updateInstalled: boolean = false;
    @observable isOfflineMode: boolean = false;

    public get isLocalhost(): boolean {
        return Boolean(
            window.location.hostname === 'localhost' ||
            // [::1] is the IPv6 localhost address.
            window.location.hostname === '[::1]' ||
            // 127.0.0.1/8 is considered localhost for IPv4.
            window.location.hostname.match(
                /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
            )
        );
    }

    public registerServiceWorker() {
        console.log('registerServiceWorker', process.env);

        // if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
            // The URL constructor is available in all browsers that support SW.
        const publicUrl = new URL(
            process.env.PUBLIC_URL!,
            window.location.toString()
        );

        if (publicUrl.origin !== window.location.origin) {
            // Our service worker won't work if PUBLIC_URL is on a different origin
            // from what our page is served on. This might happen if a CDN is used to
            // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
            return;
        }

        window.addEventListener('load', () => {
            const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

            if (this.isLocalhost) {
                // This is running on localhost. Lets check if a service worker still exists or not.
                this.checkValidServiceWorker(swUrl);

                // Add some additional logging to localhost, pointing developers to the
                // service worker/PWA documentation.
                navigator.serviceWorker.ready.then(registration => {
                    console.log(
                        'This web app is being...'
                    );
                });
            } else {
                // Is not local host. Just register service worker
                this.registerValidSW(swUrl);
            }
        });
        // }
    }

    public unregisterServiceWorker(): void {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.ready.then(registration => {
                registration.unregister();
            });
        }
    }

    public updateServiceWorker(): void {
        console.log('updateServiceWorker', navigator.serviceWorker);

        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.ready.then(registration => {
                console.log('checking for an update...');
                registration.update().then(() => {
                    console.log('...done checking for an update');
                });
            });
        }
    }

    private checkValidServiceWorker(swUrl: string) {
        this.isOfflineMode = false;

        // Check if the service worker can be found. If it can't reload the page.
        fetch(swUrl)
            .then(response => {
                // console.log('checkValidServiceWorker', response);
                // Ensure service worker exists, and that we really are getting a JS file.
                if (
                    response.status === 404 ||
                    response.headers.get('content-type')!.indexOf('javascript') === -1
                ) {
                    // No service worker found. Probably a different app. Reload the page.
                    navigator.serviceWorker.ready.then(registration => {
                        registration.unregister().then(() => {
                            window.location.reload();
                        });
                    });
                } else {
                    // Service worker found. Proceed as normal.
                    this.registerValidSW(swUrl);
                }
            })
            .catch(() => {
                console.log('No internet connection found. App is running in offline mode.');
                this.isOfflineMode = true;
            });
    }

    private registerValidSW(swUrl: string) {
        return navigator.serviceWorker
            .register(swUrl)
            .then(registration => {
                registration.onupdatefound = this.handleOnUpdateFound;
            })
            .catch(error => {
                console.error('Error during service worker registration:', error);
            });
    }

    @action private handleOnUpdateFound = (): void => {
        console.log('handleOnUpdateFound'); 

        navigator.serviceWorker.ready.then(registration => {
            console.log('handleOnUpdateFound 2', registration); 

            const installingWorker = registration.installing;

            if (installingWorker) {
                this.installingUpdate = true;

                installingWorker.onstatechange = () => {
                    if (installingWorker.state === 'installed') {
                        // console.log('navigator', navigator);
                        if (navigator.serviceWorker.controller) {
                            // At this point, the old content will have been purged and
                            // the fresh content will have been added to the cache.
                            // It's the perfect time to display a 'New content is
                            // available; please refresh.' message in your web app.
                            // console.log('New content is available; please refresh.');

                            setTimeout(() => {
                                window.location.reload();
                            // tslint:disable-next-line:align
                            }, 7000);

                        } else {
                            // At this point, everything has been precached.
                            // It's the perfect time to display a
                            // 'Content is cached for offline use.' message.
                            // console.log('Content is cached for offline use.');
                        }

                        this.updateInstalled = true;
                        this.installingUpdate = false;
                    }
                };
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

是否进行了更多的故障排除,而该故障排除不起作用的主要原因是需要设置Cache-Control: public,max-age=0(以前不是零)。 Chrome的DevTools必须在做一些事情来绕过它。