Files

69 lines
2.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useEffect } from "react";
/**
* 访客心跳(真实在线统计埋点):
* - visitorId 首次生成后写入 localStorage 持久化(匿名,无隐私信息);
* - 每 60s POST /open/visitor/ping?visitorId=x&module=<module>;
* - 页面隐藏(document.hidden)时暂停,可见时立即补一次心跳;
* - 后端以 5 分钟滑动窗口去重统计在线数。
* module:official=企业官网 / personal=个人站,与后端白名单一致。
*/
export default function VisitorHeartbeat({ module = "official" }: { module?: string }) {
useEffect(() => {
const KEY = "vhsys_visitor_id";
let visitorId = "";
try {
visitorId = localStorage.getItem(KEY) ?? "";
if (!visitorId) {
visitorId =
typeof crypto !== "undefined" && "randomUUID" in crypto
? crypto.randomUUID()
: `v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
localStorage.setItem(KEY, visitorId);
}
} catch {
// localStorage 不可用(隐私模式等):会话级一次性 id,不影响其它功能
visitorId = `s-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
// 统计接口与内容接口同源反代:优先走同域 /api,开发环境回退后端端口
const base =
typeof window !== "undefined" && window.location.hostname === "localhost"
? "http://localhost:9999/api"
: "/api";
const ping = () => {
try {
const body = new URLSearchParams({ visitorId, module });
// keepalive:页面卸载时请求也能发出
fetch(`${base}/open/visitor/ping`, {
method: "POST",
body,
keepalive: true,
}).catch(() => {});
} catch {
/* 静默:埋点失败不影响页面 */
}
};
ping();
const interval = window.setInterval(() => {
if (!document.hidden) ping();
}, 60_000);
const onVisible = () => {
if (!document.hidden) ping();
};
document.addEventListener("visibilitychange", onVisible);
return () => {
window.clearInterval(interval);
document.removeEventListener("visibilitychange", onVisible);
};
}, [module]);
return null;
}