const getParmvalByKey = function(url,_key,_separator){ let _url = url || ''; _separator = _separator || '?'; _url = _url.trim(); var _separatorIndex = _url.indexOf(_separator); if(_separatorIndex<0){ return ''; } if(_separator!='#'){ var _index = _url.indexOf('#') || 0; if(_index>=0 && _separatorIndex<_index){ _url = _url.substring(0,_index); } } _url = _url.substr(_separatorIndex+1); if (!_url) return ''; _url = _url.split('&'); for(var i=0,l=_url.length,d;i 0){ hash = '#' + url.split('#')[1] url = url.split('#')[0] } if(separatorIndex < 0){ return url + '?' + key + '=' + value + hash; }else{ var reg = new RegExp('(\\?|&)(' + key + '=(.+?))($|&|#)', 'g'); url = reg.test(url) ? url.replace(reg, '$1' + key + '=' + value + '$4') : url + '&' + key + '=' + value; return url + hash; } } const getCmsPageId = function(){ const pathName = window.location.pathname; let id = ''; try { id = pathName.split('/')[2]; } catch (e) { console.log(e); id = '0'; } return id; } const genSpmString = ({name = '', a = 0,b = 0,c = 0,d = 0}) => { const cmsId = getCmsPageId(); let spm = ''; switch(name) { case 'spmCmspageCoupon': // cms页面-优惠券模块 spm = `9.${cmsId}.1.0`; break; case 'spmCmspageProduct': // cms页面-商品模块 spm = `9.${cmsId}.2.0`; break; default: spm = ''; } return spm; } export function genSpmLink({url, name, a, b, c, d}){ const adTrace = getParmvalByKey(location.href, 'adTrace', '?') || ''; const spm = getParmvalByKey(location.href, 'spm', '?') || ''; let newSpm = genSpmString({name, a,b,c,d}); if (spm) { let spmsArr = spm.split('-'); const lastSpm = spmsArr[spmsArr.length - 1] const lastSpmArr = lastSpm.split('.') if(newSpm) { const newSpmArr = newSpm.split('.') if(newSpmArr.length === 4 && newSpmArr.length === lastSpmArr.length ) { if (newSpmArr[0] === lastSpmArr[0]) { // 同一页面 spmsArr.splice(-1, 1, newSpm) } else { spmsArr.push(newSpm) } } } newSpm = spmsArr.slice(-4).join('-'); } let newSpmLink = setParmvalByKey(url, 'spm', newSpm); if (adTrace) { newSpmLink = setParmvalByKey(newSpmLink, 'adTrace', adTrace); } // console.log(adTrace, spm, newSpm, newSpmLink); return newSpmLink; };