账户登录
This commit is contained in:
1 parent
f08dcee83a
commit
8e80e26c91
57 files changed
+1401
-100
No files matched your search
@@ -0,0 +1,164 @@
|
||||
import sensors from "sa-sdk-javascript";
|
||||
|
||||
const API_BASE = import.meta.env.VITE_SITE_API_BASE || "/api/site/v1";
|
||||
const SESSION_TIMEOUT = 30 * 60 * 1000;
|
||||
const VISITOR_KEY = "shoplix_analytics_visitor";
|
||||
const SESSION_KEY = "shoplix_analytics_session";
|
||||
const SESSION_TIME_KEY = "shoplix_analytics_session_time";
|
||||
const LANDING_KEY = "shoplix_analytics_landing";
|
||||
|
||||
type EventProperties = Record<string, string | number | boolean | undefined>;
|
||||
|
||||
/** 页面访问上下文。 */
|
||||
export type PageAnalyticsContext = {
|
||||
pageCode: string;
|
||||
pageName: string;
|
||||
targetCode?: string;
|
||||
scene?: string;
|
||||
};
|
||||
|
||||
let initialized = false;
|
||||
let pageStartTime = Date.now();
|
||||
|
||||
/** 初始化神策Web SDK并将数据发送到项目自建接收端。 */
|
||||
export function initializeAnalytics(): void {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
const visitor = ensureVisitor();
|
||||
const session = ensureSession();
|
||||
sensors.init({
|
||||
server_url: new URL(`${API_BASE}/analytics/beacon-report-flow`, location.origin).href,
|
||||
send_type: "ajax",
|
||||
batch_send: false,
|
||||
show_log: import.meta.env.DEV,
|
||||
is_track_single_page: false,
|
||||
use_client_time: true,
|
||||
});
|
||||
sensors.identify(visitor.code, true);
|
||||
sensors.registerPage({
|
||||
language: document.documentElement.lang || "en",
|
||||
session_id: session.code,
|
||||
is_new_visitor: visitor.isNew ? 1 : 0,
|
||||
is_session_first: session.isFirst ? 1 : 0,
|
||||
landing_domain: landing().host,
|
||||
landing_url: landing().href,
|
||||
landing_url_body: landing().pathname,
|
||||
});
|
||||
}
|
||||
|
||||
/** 上报页面访问事件。 */
|
||||
export function trackPageView(context: PageAnalyticsContext): void {
|
||||
initializeAnalytics();
|
||||
pageStartTime = Date.now();
|
||||
sensors.track("PageView", commonProperties(context));
|
||||
markSessionVisited();
|
||||
}
|
||||
|
||||
/** 上报页面离开事件及停留时长。 */
|
||||
export function trackPageLeave(context: PageAnalyticsContext): void {
|
||||
const now = Date.now();
|
||||
sensors.track("PageLeave", {
|
||||
...commonProperties(context),
|
||||
start_time: pageStartTime,
|
||||
duration: Math.max(0, Math.round((now - pageStartTime) / 1000)),
|
||||
});
|
||||
}
|
||||
|
||||
/** 上报询盘提交成功事件。 */
|
||||
export function trackInquirySubmitted(inquiryCode: string, scene: string): void {
|
||||
sensors.track("SubmitInquiry", {
|
||||
...commonProperties({ pageCode: routePageCode(), pageName: document.title, scene }),
|
||||
event_detail: inquiryCode,
|
||||
});
|
||||
}
|
||||
|
||||
/** 上报通用点击事件。 */
|
||||
export function trackClick(detail: string, properties: EventProperties = {}): void {
|
||||
sensors.track("Click", { ...commonProperties({ pageCode: routePageCode(), pageName: document.title }), event_detail: detail, ...properties });
|
||||
}
|
||||
|
||||
/** 创建当前页面公共属性。 */
|
||||
function commonProperties(context: PageAnalyticsContext): EventProperties {
|
||||
const url = new URL(location.href);
|
||||
const connection = (navigator as Navigator & { connection?: { effectiveType?: string } }).connection;
|
||||
return {
|
||||
page_code: context.pageCode,
|
||||
page_name: context.pageName,
|
||||
target_code: context.targetCode,
|
||||
scene: context.scene,
|
||||
start_time: pageStartTime,
|
||||
pixel_ratio: String(window.devicePixelRatio || 1),
|
||||
domain: url.host,
|
||||
url_args: url.search,
|
||||
win_height: window.innerHeight,
|
||||
win_width: window.innerWidth,
|
||||
network: connection?.effectiveType,
|
||||
utm_source: url.searchParams.get("utm_source") || undefined,
|
||||
utm_campaign: url.searchParams.get("utm_campaign") || undefined,
|
||||
utm_adgroup: url.searchParams.get("utm_adgroup") || undefined,
|
||||
flow_channel: flowChannel(document.referrer),
|
||||
social_media_channel: socialChannel(document.referrer),
|
||||
};
|
||||
}
|
||||
|
||||
/** 获取或创建匿名访客。 */
|
||||
function ensureVisitor(): { code: string; isNew: boolean } {
|
||||
const existing = localStorage.getItem(VISITOR_KEY);
|
||||
if (existing) return { code: existing, isNew: false };
|
||||
const code = crypto.randomUUID();
|
||||
localStorage.setItem(VISITOR_KEY, code);
|
||||
return { code, isNew: true };
|
||||
}
|
||||
|
||||
/** 获取或创建三十分钟有效的会话。 */
|
||||
function ensureSession(): { code: string; isFirst: boolean } {
|
||||
const now = Date.now();
|
||||
const previousTime = Number(sessionStorage.getItem(SESSION_TIME_KEY) || 0);
|
||||
let code = sessionStorage.getItem(SESSION_KEY);
|
||||
let isFirst = sessionStorage.getItem(`${SESSION_KEY}_visited`) !== "1";
|
||||
if (!code || now - previousTime > SESSION_TIMEOUT) {
|
||||
code = crypto.randomUUID();
|
||||
sessionStorage.setItem(SESSION_KEY, code);
|
||||
sessionStorage.removeItem(`${SESSION_KEY}_visited`);
|
||||
isFirst = true;
|
||||
}
|
||||
sessionStorage.setItem(SESSION_TIME_KEY, String(now));
|
||||
return { code, isFirst };
|
||||
}
|
||||
|
||||
/** 标记当前会话已产生页面访问。 */
|
||||
function markSessionVisited(): void {
|
||||
sessionStorage.setItem(`${SESSION_KEY}_visited`, "1");
|
||||
sessionStorage.setItem(SESSION_TIME_KEY, String(Date.now()));
|
||||
}
|
||||
|
||||
/** 获取首次落地页。 */
|
||||
function landing(): URL {
|
||||
const stored = sessionStorage.getItem(LANDING_KEY);
|
||||
if (stored) return new URL(stored);
|
||||
sessionStorage.setItem(LANDING_KEY, location.href);
|
||||
return new URL(location.href);
|
||||
}
|
||||
|
||||
/** 判断流量渠道。 */
|
||||
function flowChannel(referrer: string): string {
|
||||
if (!referrer) return "DIRECT";
|
||||
const host = new URL(referrer).hostname.toLowerCase();
|
||||
if (/google|bing|yahoo|baidu|yandex/.test(host)) return "ORGANIC_SEARCH";
|
||||
if (/facebook|instagram|linkedin|twitter|x\.com|youtube|tiktok/.test(host)) return "SOCIAL";
|
||||
return "REFERRAL";
|
||||
}
|
||||
|
||||
/** 判断社媒来源。 */
|
||||
function socialChannel(referrer: string): string | undefined {
|
||||
const match = referrer.toLowerCase().match(/facebook|instagram|linkedin|twitter|youtube|tiktok/);
|
||||
return match?.[0];
|
||||
}
|
||||
|
||||
/** 根据当前路径识别页面类型。 */
|
||||
export function routePageCode(): string {
|
||||
const paths = location.pathname.split("/").filter(Boolean);
|
||||
if (!paths.length) return "HOME";
|
||||
const mapping: Record<string, string> = { products: "PRODUCT", news: "NEWS", cases: "CASE", help: "HELP" };
|
||||
return mapping[paths[0]] ? `${mapping[paths[0]]}_${paths[1] ? "DETAIL" : "CATEGORY"}` : "CUSTOM_PAGE";
|
||||
}
|
||||
Reference in new issue
Block a user