pwa.js 2.51 KB
import $ from 'yoho-jquery';
import yoho from 'yoho-app';

const isHttps = location.protocol === 'https:';

function register() {
    const t = window.STATIC_RESOURCE_HASH || '';
    const staticServer = window.STATIC_RESOURCE_PATH || '';

    if (navigator && navigator.serviceWorker && navigator.serviceWorker.register) {
        navigator.serviceWorker.register(`/sw.js?t=${t}&staticServer=${staticServer}`, {
            scope: '/'
        }).then(() => {
            if (window._hmt && window._hmt.push) {
                window._hmt.push(['_trackEvent', 'SW registered', 'SUCCESS',
                    document.title, location.href]);
            }
        }).catch(err => {
            if (window._hmt && window._hmt.push) {
                window._hmt.push(['_trackEvent', 'SW registered', 'FAILED',
                    document.title, JSON.stringify(err)]);
            }
        });
    }
}

function unregister() {
    if (isHttps && navigator && navigator.serviceWorker && navigator.serviceWorker.getRegistrations) {
        navigator.serviceWorker.getRegistrations().then(registrations => {
            for (let registration of registrations) {
                registration.unregister().then(() => {
                    if (window._hmt && window._hmt.push) {
                        window._hmt.push(['_trackEvent', 'SW unregistered', 'SUCCESS',
                            document.title, location.href]);
                    }
                }).catch(err => {
                    if (window._hmt && window._hmt.push) {
                        window._hmt.push(['_trackEvent', 'SW unregistered', 'FAILED',
                            document.title, JSON.stringify(err)]);
                    }
                });
            }
        });
    }
}

window.addEventListener('load', function() {
    // Android WebView 中 UserAgent 不正确
    if (!yoho.isApp && !(yoho.isAndroid && yoho.isWechat)) {
        if ('serviceWorker' in navigator && isHttps) {
            $.ajax({
                url: '//m.yohobuy.com/api/switch',
                dataType: 'jsonp',
                cache: false,
                success(res) {
                    const usePwa = isHttps && res && res.usePwa;

                    if (usePwa) {
                        register();
                    } else {
                        unregister();
                    }
                }
            });
        }
    }
});

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