Appearance
Session 汇报
上报用户会话信息,用于追踪用户活跃度和行为分析。
基本用法
javascript
await sdk.reportSession({
urlPath: window.location.pathname,
viewport: {
width: window.innerWidth,
height: window.innerHeight
}
});完整参数
javascript
await sdk.reportSession({
urlPath: '/dashboard', // 当前页面路径(可选)
viewport: { // 视口尺寸(可选)
width: 1920,
height: 1080
},
customData: { // 自定义数据(可选)
theme: 'dark',
language: 'zh-CN',
referrer: document.referrer
}
});应用启动时上报
javascript
window.addEventListener('load', () => {
if (sdk.isLoggedIn()) {
sdk.reportSession({
urlPath: window.location.pathname,
viewport: {
width: window.innerWidth,
height: window.innerHeight
}
});
}
});页面跳转时上报
Vue Router 示例
javascript
router.afterEach((to) => {
if (sdk.isLoggedIn()) {
sdk.reportSession({
urlPath: to.path
}).catch(err => console.warn('会话上报失败', err));
}
});React Router 示例
javascript
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function useSessionReport() {
const location = useLocation();
useEffect(() => {
if (sdk.isLoggedIn()) {
sdk.reportSession({
urlPath: location.pathname
}).catch(err => console.warn('会话上报失败', err));
}
}, [location]);
}定期上报保持活跃
javascript
// 每 5 分钟上报一次
setInterval(() => {
if (sdk.isLoggedIn()) {
sdk.reportSession({
urlPath: window.location.pathname
}).catch(err => console.warn('会话上报失败', err));
}
}, 5 * 60 * 1000);监听窗口大小变化
javascript
window.addEventListener('resize', () => {
if (sdk.isLoggedIn()) {
sdk.reportSession({
viewport: {
width: window.innerWidth,
height: window.innerHeight
}
});
}
});错误处理
javascript
try {
await sdk.reportSession({
urlPath: window.location.pathname
});
console.log('会话上报成功');
} catch (error) {
if (error.code === 'UNAUTHORIZED') {
console.error('Token 已过期,请重新登录');
sdk.logout();
// 重定向到登录页
window.location.href = '/login';
} else {
console.error('会话上报失败:', error.message);
}
}注意事项
- 需要先登录(Token 有效)才能上报会话
- 如果 Token 已过期,会抛出
UNAUTHORIZED错误 - 建议在关键页面跳转时调用,不要过于频繁
- 应用启动时建议上报一次
- 可以定期上报以保持用户活跃状态