global.js 1.96 KB
/**
 * 全局引用js
 * @author: feng.chen<feng.chen@yoho.cn>
 * @date: 2017/03/15
 */
const $ = require('yoho-jquery');
const cookie = require('yoho-cookie');
const qs = require('yoho-qs');
const tip = require('plugin/tip');
const yoho = require('./yoho-app');

require('./pwa/pwa');
require('./common/back-download');

// 如果不是 App,就把这个 cookie 清理掉,解决之前缓存错误的问题 20171020
const isApp = qs.app_version || /YohoBuy/i.test(navigator.userAgent || '');

if (!isApp) {
    cookie.remove('app_uid', 'app_version', 'app_client_type');
}

// App 的信息需要存下来
if (yoho.isApp && qs.uid && qs.app_version && qs.client_type) {
    const options = {
        path: '/'
    };

    // 如果 App 没有写 UID,或者写的不对,H5 写一下
    if (!cookie.get('app_uid') || cookie.get('app_uid') === '0') {
        qs.uid && cookie.set('app_uid', qs.uid, options);
        qs.app_version && cookie.set('app_version', qs.app_version, options);
        qs.client_type && cookie.set('app_client_type', qs.client_type, options);
        qs.session_key && cookie.set('app_session_key', qs.session_key, options);
    }
}

// 注册ajaxError处理服务端401状态
$(document).ajaxError((event, xhr) => {
    if (xhr.status === 401) {
        if (xhr.responseJSON && xhr.responseJSON.lowVersion) {
            tip.show(xhr.responseJSON.message);
        } else {
            cookie.remove('_UID');
            cookie.remove('_TOKEN');

            if (yoho.isApp) {
                yoho.goLogin(window.location.href);
            } else {
                window.location.href = `/signin.html?refer=${encodeURIComponent(window.location.href)}`;
            }
        }
    } else if (xhr.status === 403 && xhr.responseJSON.code === 4403) {
        tip.show(xhr.responseJSON.message);
        setTimeout(function() {
            window.location.href = `${xhr.responseJSON.data.url}&refer=${encodeURIComponent(window.location.href)}`;
        }, 2000);
    }
});