| 123456789101112131415161718192021222324252627282930313233343536373839 |
- // 商品浏览停留时长埋点工具
- // 用法(商品详情页):
- // onLoad: startProductDwell()
- // onUnload: flushProductDwell(this.product)
- // 后端接口:POST /api/stats/product-view(StatsController.recordProductView)
- import { reportProductDwell } from './api.js'
- let _startTs = 0
- export function startProductDwell() {
- _startTs = Date.now()
- }
- export function flushProductDwell(product) {
- var start = _startTs
- _startTs = 0
- if (!product || !product.id) return
- // 未调用 startProductDwell 时不得上报:此前 start=0 会把 Date.now() 当成停留时长(≈17 亿秒)
- if (!start) return
- var duration = Math.round((Date.now() - start) / 1000)
- if (duration <= 0) return
- // 单次停留上限 30 分钟:小程序切后台/锁屏时计时仍在走,避免产生超长时长
- if (duration > 1800) duration = 1800
- var userId = 0
- try {
- userId = uni.getStorageSync('userId') || 0
- } catch (e) {}
- var payload = {
- userId: userId,
- productId: product.id,
- productName: product.name || '',
- productType: product.productType || '',
- durationSeconds: duration,
- source: 'miniprogram'
- }
- try {
- reportProductDwell(payload)
- } catch (e) {}
- }
|