在用户购票时,需区分销售渠道,通过在url上增加查询参数并存储到cookie的方式,实现了用户归属
- 获取url上的查询参数
export const getQueryString = () => {
// 定义返回结果
const result: any = {};
// 获取url上的参数(使用decodeURIComponent对url参数进行解码)
const search = decodeURIComponent(window.location.search);//?a=1&b=2
const tempArr = search !== "" ? search.substr(1).split("&") : [];//a=1 b=2
tempArr.forEach((item) => {
if (item) {
// 将参数名和参数值拆分
const itemArr = item.split("=");
// 参数名作为key, 参数值为value
// eslint-disable-next-line prefer-destructuring
result[itemArr[0]] = itemArr[1];
}
});
return result;
};
- 存储到 cookie
// 检查 URL 中的 source 参数
const query = getQueryString();
if (query?.source) {
// 设置 cookie,48小时过期
const expires = new Date();
expires.setTime(expires.getTime() + (48 * 60 * 60 * 1000)); // 48小时
document.cookie = `source=${query?.source}; expires=${expires.toUTCString()}; path=/`;
}