dwellTracker.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // 商品浏览停留时长埋点工具
  2. // 用法(商品详情页):
  3. // onLoad: startProductDwell()
  4. // onUnload: flushProductDwell(this.product)
  5. // 后端接口:POST /api/stats/product-view(StatsController.recordProductView)
  6. import { reportProductDwell } from './api.js'
  7. let _startTs = 0
  8. export function startProductDwell() {
  9. _startTs = Date.now()
  10. }
  11. export function flushProductDwell(product) {
  12. var start = _startTs
  13. _startTs = 0
  14. if (!product || !product.id) return
  15. // 未调用 startProductDwell 时不得上报:此前 start=0 会把 Date.now() 当成停留时长(≈17 亿秒)
  16. if (!start) return
  17. var duration = Math.round((Date.now() - start) / 1000)
  18. if (duration <= 0) return
  19. // 单次停留上限 30 分钟:小程序切后台/锁屏时计时仍在走,避免产生超长时长
  20. if (duration > 1800) duration = 1800
  21. var userId = 0
  22. try {
  23. userId = uni.getStorageSync('userId') || 0
  24. } catch (e) {}
  25. var payload = {
  26. userId: userId,
  27. productId: product.id,
  28. productName: product.name || '',
  29. productType: product.productType || '',
  30. durationSeconds: duration,
  31. source: 'miniprogram'
  32. }
  33. try {
  34. reportProductDwell(payload)
  35. } catch (e) {}
  36. }