util.js 8.84 KB
/**
 * 采集系统的工具库
 */

var cookie = require('./cookie');

//flash监测
exports.flashChecker = function() {
    var hasFlash = 0; //是否安装了flash
    var flashVersion = 0; //flash版本
    var isIE = /*@cc_on!@*/ 0; //是否IE浏览器
    var swf = null;
    if (isIE) {
        swf = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
        if (swf) {
            hasFlash = 1;
            flashVersion = swf.GetVariable("$version");
        }
    } else {
        if (navigator.plugins && navigator.plugins.length > 0) {
            swf = navigator.plugins["Shockwave Flash"];
            if (swf) {
                hasFlash = 1;
                flashVersion = swf.description.replace("Shockwave Flash", '');
            }
        }
    }
    return {
        f: hasFlash,
        v: flashVersion
    };
};

//hash算法
exports.Hash = function(str) {
    var hash = 1,
        charCode = 0,
        idx;
    if (str) {
        hash = 0;
        for (idx = str.length - 1; idx >= 0; idx--) {
            charCode = str.charCodeAt(idx);
            hash = (hash << 6 & 268435455) + charCode + (charCode << 14);
            charCode = hash & 266338304;
            if (charCode !== 0) {
                hash = hash ^ charCode >> 21;
            }
        }
    }
    return hash;
};

//生成随机数
exports.Random = function() {
    return Math.round(Math.random() * 2147483647);
};

//hash客户端信息
exports.hashClientInfo = function() {
    var navigator = window.navigator;
    var history_length = window.history.length;
    var arr = [
        navigator.appName,
        navigator.version,
        navigator.language,
        navigator.platform,
        navigator.userAgent,
        navigator.javaEnabled(),
        window.screen,
        window.screen.colorDepth, (window.document.cookie ? window.document.cookie : ""), (window.document.referrer ? window.document.referrer : "")
    ];

    navigator = arr.join('');

    for (var len = navigator.length; history_length > 0;) {
        navigator += history_length-- ^ len++;
    }
    return exports.Hash(navigator);
};

//浅层合并对象
exports.merge = function(obj1, obj2) {
    var ret = {};
    for (var attr in obj1) {
        ret[attr] = obj1[attr];
    }

    for (var attr2 in obj2) {
        ret[attr2] = obj2[attr2];
    }
    return ret;
};

//生成URL键值对
exports.genParam = function(obj) {
    var arr = [];
    for (var key in obj) {
        arr.push(key + '=' + obj[key]);
    }
    return arr.join('&');
};

//除去字符串前后的空格
exports.trim = function(text) {
    if (String.prototype.trim) {
        return text === null ? "" : String.prototype.trim.call(text);
    } else {
        var trimLeft = /^\s+/;
        var trimRight = /\s+$/;
        var ret = '';
        if (text) {
            ret = text.toString().replace(trimLeft, "");
            ret = ret.replace(trimRight, "");
            return ret;
        }
    }
};

//获取地理位置信息
exports.getGeo = function(callback) {
    if (window.navigator.geolocation) {
        var options = {
            enableHighAccuracy: true,
        };
        window.navigator.geolocation.getCurrentPosition(handleSuccess, handleError, options);
    } else {
        callback(false);
    }

    function handleSuccess(position) {
        // 获取到当前位置经纬度  本例中是chrome浏览器取到的是google地图中的经纬度
        var lng = position.coords.longitude;
        var lat = position.coords.latitude;
        callback(lat, lng);
    }

    function handleError(error) {
        callback(false);
    }
};

exports.queryString = function() {
    var vars = {},
        hash,
        i;
    var hashes = window.location.search.slice(1).split('&');

    for (i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars[hash[0]] = hash[1];
    }
    return vars;
};

exports.closest = function(el, selector) {
    var matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;

    while (el) {
        if (matchesSelector.call(el, selector)) {
            break;
        }
        el = el.parentElement;
    }
    return el;
};

exports.getChannel = function() {
    // function cookie(name) {
    //   var cookies = document.cookie,
    //     cookieVal;

    //   if (cookies) {
    //     cookies = cookies.split(';');
    //     cookies.forEach(function(c) {
    //       if (c.indexOf(name) > -1) {
    //         cookieVal = decodeURIComponent(c.replace(name + '=', '').trim());
    //         return;
    //       }
    //     });
    //   }

    //   return cookieVal;
    // }

    return {
      men: 1,
      women: 2,
      boys: 1,
      girls: 2,
      kids: 3,
      lifestyle: 4
    }[cookie('_Channel') || 'boys'];
}

var _getAppVersionByUa = function() {
    var vars = navigator.userAgent.split(';') || [];
    for (var i = 0; i < vars.length; i++) {
        if (vars[i].indexOf('app_version') > -1) {
            return vars[i].split('=')[1];
        }
    }
}

exports.getAppVersion = function() {
    var appVer = window.qs.app_version || window.qs.appVersion;
    // if (!appVer) {
    //     appVer = _getAppVersionByUa();
    // }
    return appVer;
}

/**
 * 从referrer中获取信息,设定mktcode
 */
var channelMap = {
    "baidu.com": 100000000000055,
    "so.com": 100000000000049,
    "sogou.com": 100000000000053,
    "bing.com": 100000000000057,
    "m.sm.cn": 100000000000059,
    "google.com": 100000000000061
};

var isMobile = 'm.yohobuy.com' === location.hostname || /\.m\.yohobuy\.com$/.test(location.hostname);

if (!isMobile) {
    // PC 使用单独的推广码
    channelMap = {
        "baidu.com": 100000000008051,
        "so.com": 100000000008043,
        "sogou.com": 100000000008049,
        "bing.com": 100000000008045,
        "m.sm.cn": 100000000008053,
        "google.com": 100000000008047
    };
}

exports.getMktcBySeo = function() {
    var mktc,
        rf = document.referrer;

    for (var domain in channelMap) {
        if (rf.indexOf(domain) > -1) {
            mktc = channelMap[domain];
            break;
        }
    }
    return mktc;
}

/**
 * 动态添加下载条
 */
exports.setFontSize = function() {
    var e = document.documentElement;
    if (!e.style.fontSize) {
        var f = e.clientWidth;
        if (!f) {
            return
        }
        if (f >= 640) {
            e.style.fontSize = "40px";
        } else {
            e.style.fontSize = 40 * (f / 640) + "px";
        }
    }
}

exports.getMiniAppDialog = function() {
    var imgpath = '//cdn.yoho.cn/static/wechat/miniapp-yohobuy.jpg?imageView2/1/w/258/h/258&t=' + (new Date().getTime());
    var minipath = document.getElementById('main-wrap').getAttribute('data-minipath') || imgpath;
    var str = '<div class="mini-app-dialog-bg" id="mini-app-dialog-bg"></div>';

    str += '<div class="mini-app-dialog" id="mini-app-dialog">';
    str += '<div class="mini-app-header"><span class="mini-app-close" id="mini-app-close"></span></div>';
    str += '<div class="mini-app-content"><img id="mini-app-img" src="' + minipath + '" onerror="this.src= \'' + imgpath + '\';this.onerror=null;" /></div>';
    str += '<div class="mini-app-footer">长按识别小程序码进入</div>';
    str += '</div>';
    return str;
}

exports.getDownloadStr = function(isWechat) {
    var str = '<div class="top-downloadbar';

    if (isWechat) {
        str += ' top-downloadbar-wechat';
    }

    str += '" id="top-downloadbar"><a href="javascript:void(0);" class="download-close" id="download-close"></a>\
    <span class="download-icon"></span>';
    if (isWechat) {
        str += '<span class="download-text">Yoho!Buy有货</span>';
        str += '<span class="download-text-desc">新人领499元礼包</span>';
        str += '<a class="download-go-wechat" id="download-go" href="https://union.yoho.cn/union/app-downloads.html">下载领取</a>';
        str += '<a class="mini-app-open" id="mini-app-open" href="javascript:;">小程序打开</a>';
        // str += '<a class="download-wechat" id="download-wechat" href="https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MjM5ODI5MDA4MA==&scene=110#wechat_redirect">加关注</a></div>';
    } else {
        str += '<span class="download-text">Yoho!Buy有货 潮流购物逛不停</span>';
        str += '<p class="download-text-desc">新人领499元礼包</p>';
        str += '<a class="download-go" id="download-go" href="https://union.yoho.cn/union/app-downloads.html">下载领取</a></div>';
    }

    return str;
}

exports.getAppPath = function() {
    var dataSet = document.getElementById('main-wrap').dataset || {};
    var appPath = dataSet.apppath;
    
    appPath = (appPath || '').replace('yohobuy://yohobuy.com/goapp?','') || 'openby:yohobuy={"action":"go.home","params":{"gender":"1","channel":"2"}}';
    return appPath;
}

exports.getUdid = function() {
    // YAS 上报接口 当前的 udid
    var udid = cookie('udid') || '';

    return udid || 0;
}