dwellTracker.js 933 B

1234567891011121314151617181920212223242526272829303132333435
  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. var duration = Math.round((Date.now() - start) / 1000)
  16. if (duration <= 0) return
  17. var userId = 0
  18. try {
  19. userId = uni.getStorageSync('userId') || 0
  20. } catch (e) {}
  21. var payload = {
  22. userId: userId,
  23. productId: product.id,
  24. productName: product.name || '',
  25. productType: product.productType || '',
  26. durationSeconds: duration,
  27. source: 'miniprogram'
  28. }
  29. try {
  30. reportProductDwell(payload)
  31. } catch (e) {}
  32. }