修复访客浏览轨迹延迟与排序,增加演示站

保留 SPA hash 以正确区分页面;延迟采集 title 避免慢一页;轨迹改为最新在上;补充 demo-shop 测试页与 Vite 静态路由。
This commit is contained in:
yml2213
2026-07-18 23:22:47 +08:00
parent 81852e0ddd
commit 970bae16d1
9 changed files with 651 additions and 44 deletions
+29 -8
View File
@@ -135,7 +135,7 @@ const VisitorChat = ({
title: initialPage?.title || (typeof document !== 'undefined' ? document.title : ''),
referrer: initialPage?.referrer || (typeof document !== 'undefined' ? document.referrer : ''),
})
const lastPageURLRef = useRef('')
const lastPageKeyRef = useRef('') // url + title,避免同 URL 标题更新被吞
/** 本地已同步到的最大 seq(从缓存消息初始化) */
const lastSeqRef = useRef((() => {
try {
@@ -315,11 +315,23 @@ const VisitorChat = ({
const reportPageView = useCallback(async (url: string, title: string) => {
const sid = sessionIdRef.current
const token = visitorTokenRef.current
if (!sid || !token || !url || sessionEnded) return
if (url === lastPageURLRef.current) return
lastPageURLRef.current = url
if (!url) return
// 会话尚未 Init 完成:只缓存宿主页,避免丢掉打开前/初始化中的换页
if (!sid || !token) {
hostPageRef.current = {
...hostPageRef.current,
url,
title: title || hostPageRef.current.title,
}
return
}
if (sessionEnded) return
const key = `${url}\0${title || ''}`
// 同 URL 但标题变了仍要上报(服务端会更新 current_title;新 URL 会插轨迹)
if (key === lastPageKeyRef.current) return
lastPageKeyRef.current = key
try {
await fetch('/api/widget/pageview', {
const res = await fetch('/api/widget/pageview', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -332,8 +344,11 @@ const VisitorChat = ({
page_title: title || '',
}),
})
if (!res.ok) {
lastPageKeyRef.current = ''
}
} catch {
/* 轨迹失败不影响会话 */
lastPageKeyRef.current = ''
}
}, [sessionEnded])
@@ -378,9 +393,15 @@ const VisitorChat = ({
localStorage.setItem(tokenKey, token)
localStorage.removeItem(msgsKey)
lastSeqRef.current = 0
if (page.url) lastPageURLRef.current = page.url
// init 已写入落地页;标记已上报,避免立刻重复;宿主若已换页则补报
const latest = hostPageRef.current
if (page.url) lastPageKeyRef.current = `${page.url}\0${page.title || ''}`
await loadMessages(sid, token, { full: true })
}, [channelKey, loadMessages, storageKey, tokenKey, msgsKey])
if (latest.url && (latest.url !== page.url || (latest.title || '') !== (page.title || ''))) {
lastPageKeyRef.current = ''
void reportPageView(latest.url, latest.title || '')
}
}, [channelKey, loadMessages, storageKey, tokenKey, msgsKey, reportPageView])
const closeSocket = useCallback(() => {
const sock = socketRef.current