pwa.js 1.32 KB
const isHttps = location.protocol === 'https:';
const usePwa = isHttps;

window.addEventListener('load', function() {
    if ('serviceWorker' in navigator) {
        if (usePwa) {
            const t = window.STATIC_RESOURCE_HASH || '';
            const staticServer = window.STATIC_RESOURCE_PATH || '';

            navigator.serviceWorker.register(`/sw.js?t=${t}&staticServer=${staticServer}`, {
                scope: '/'
            }).then(function(registration) {
                console.log('SW registered: ', registration);
            }).catch(err => {
                console.log('SW registration failed: ', err);
            });
        } else {
            if (isHttps) {
                navigator.serviceWorker.getRegistrations().then(function(registrations) {
                    for (let registration of registrations) {
                        registration.unregister().then(result => {
                            console.log('SW unregisted: ', result);
                        }).catch(err => {
                            console.log('SW unregistration failed: ', err);
                        });
                    }
                });
            }
        }
    }
});

// 暂时不自动弹出添加到桌面按钮
window.addEventListener('beforeinstallprompt', function(e) {
    e.preventDefault();
    return false;
});