pwa.js 2.14 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 || '';

    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.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() {
    if ('serviceWorker' in navigator && isHttps) {
        $.ajax({
            url: '//m.yohobuy.com/api/switch',
            dataType: 'jsonp',
            cache: false,
            success(res) {
                const usePwa = isHttps && !yoho.isApp && res && res.usePwa;

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

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