import Cookies from 'js-cookie'; export function getUrlParam(key) { const href = window.location.href; const url = href.split('?'); if (url.length <= 1) { return ''; } const params = url[1].split('&'); for (let i = 0; i < params.length; i++) { const param = params[i].split('='); if (key === param[0]) { return param[1]; } } return ''; } export function getIdentifierKey() { let identifierKey = 'identifier'; const domain = window.location.host; const match = domain.match(/-((stg)|(pre)|(gra)|(dev))/g); if (match) { identifierKey = (identifierKey + match[0].replace('-', '_')).replace('_pre', '_pre_1'); } else if (domain.includes('localhost') || domain.includes('172.30.66.168')) { identifierKey = identifierKey + '_local'; } // else { // // 如果是本地的地址访问也应该存 // identifierKey = identifierKey + "_local"; // } return identifierKey; } export function getRootDomain() { let rootDomain = ''; const domain = window.location.host; if (domain.includes('localhost')) { rootDomain = 'localhost'; } else if (domain.includes('172.30.66.168')) { rootDomain = '172.30.66.168'; } else { const temp = domain.split('.').reverse(); rootDomain = `.${temp[1]}.${temp[0]}`; } return rootDomain; } const identifierKey = getIdentifierKey(); const rootDomain = getRootDomain(); export function getToken() { const identifier = getUrlParam('identifier'); // 1 // const account = getUrlParam('account'); if (identifier) { setToken(identifier); const href = window.location.href; const url = href.split('?'); // 没携带query参数 if (url[1].startsWith('account')) { window.location.href = url[0]; // 携带了1个或者多个query参数 } else { let param = ''; const paramArr = url[1].split('&'); const index = paramArr.findIndex((item) => { return item.startsWith('account'); }); for (let i = 0; i < index; i++) { if (i === index - 1) { param += paramArr[i]; } else { param += paramArr[i] + '&'; } } window.location.href = url[0] + '?' + param; } } const ca = document.cookie.split(';'); const cookiesMap: Record = {}; for (let i = 0; i < ca.length; i++) { const c = ca[i]; if (c.trim()) { const [ckey, cvalue] = c.split('='); cookiesMap[ckey.trim()] = cvalue.trim(); } if (cookiesMap[identifierKey]) { return cookiesMap[identifierKey]; } } setToken(cookiesMap.identifier || ''); return cookiesMap.identifier || ''; } export function removeToken() { Cookies.remove(identifierKey); } export function setToken(identifier) { // document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; document.cookie = `${identifierKey}=${identifier};path=/;domain=${rootDomain}`; } export default { getToken, removeToken, };