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

const canUse = location.protocol === 'https:' || location.hostname === 'localhost';
const isDev = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;

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

function unregister() {
    if (canUse && 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) {
            $.ajax({
                url: '//m.yohobuy.com/api/switch',
                dataType: 'jsonp',
                cache: false,
                success(res) {
                    const usePwa = res && res.usePwa;

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

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