npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ontrack-sdk

v1.0.1

Published

埋点SDK

Readme

OnTrack 埋点SDK

OnTrack 是一个轻量级的前端埋点SDK,提供自动化的用户行为跟踪、性能监控和错误捕获功能,特别适合Vue等单页面应用。

功能特点

  • 全自动埋点:自动捕获页面访问、元素点击、接口请求等行为
  • Vue路由支持:完美适配Vue的Hash模式和History模式路由
  • 用户信息管理:跟踪用户登录状态和用户属性
  • 错误监控:自动捕获JavaScript错误和Promise异常
  • 接口性能:监控AJAX请求的性能和状态
  • 批量上报:支持事件批量发送和失败重试
  • 离线缓存:断网情况下本地存储事件,网络恢复后自动发送
  • 高可靠传输:使用图片请求方式上报,确保页面关闭时数据不丢失

安装

npm install OnTrack-sdk

或使用yarn:

yarn add OnTrack-sdk

快速开始

基础初始化

import { OnTrack } from 'OnTrack-sdk';

// 初始化SDK
OnTrack.init({
  appId: 'your-app-id',    // 应用ID
  serverUrl: 'https://your-api-endpoint.com/collect', // 数据上报地址
  
  // 可选配置
  autoTrack: true,         // 是否启用自动埋点
  batchSize: 10,           // 批量上报阈值
  batchInterval: 5000,     // 上报间隔(毫秒)
  debug: false,            // 调试模式
});

用户标识

用户登录后设置用户信息:

// 用户登录后
OnTrack.setUser({
  userId: 'user123',       // 用户ID
  username: '张三',        // 用户名
  role: 'member',          // 角色
  
  // 可添加任意其他用户属性
  level: 'vip',
  age: 28,
  region: '北京'
});

用户登出时清除信息:

// 用户登出时
OnTrack.clearUser();

手动埋点

除了自动埋点外,您也可以在需要的地方手动埋点:

// 跟踪自定义事件
OnTrack.track({
  eventName: 'product_purchase',
  properties: {
    productId: '12345',
    productName: '高级会员',
    price: 199,
    currency: 'CNY',
    paymentMethod: 'wechat'
  }
});

高级配置

完整配置选项

OnTrack.init({
  // 必填配置
  appId: 'your-app-id',
  serverUrl: 'https://your-api-endpoint.com/collect',
  
  // 自动埋点配置
  autoTrack: {  // 可设为true/false或详细配置对象
    pageView: true,  // 页面访问跟踪
    click: true,     // 点击事件跟踪
    xhr: true,       // 接口请求跟踪
    error: true      // 错误监控
  },
  
  // 批量上报配置
  batchSize: 10,       // 达到10条数据时立即上报
  batchInterval: 5000, // 每5秒检查一次是否需要上报
  
  // 调试配置
  debug: false,        // 开启后会在控制台打印详细日志
  
  // 初始用户信息(可选)
  userInfo: {
    userId: 'anonymous123',
    isAnonymous: true
  }
});

自动采集的事件

SDK会自动采集以下事件:

1. 页面访问事件 (page_view)

记录用户访问的页面信息,包含多种访问类型:

  • page_load: 初始页面加载
  • hash_route_change: Hash路由变化 (Vue的hash模式)
  • history_route_change: History API变化 (Vue的history模式)
  • vue_route_change: Vue路由变化 (通过DOM变化检测)
{
  "eventName": "page_view",
  "properties": {
    "url": "https://example.com/#/product/123",
    "path": "/",
    "hash": "#/product/123",
    "query": "?from=home",
    "title": "产品详情",
    "referrer": "https://example.com/#/home",
    "viewType": "hash_route_change",
    "fromHash": "#/home",
    "toHash": "#/product/123",
    "timestamp": 1647123456789,
    "user": {
      "userId": "user123",
      "username": "张三",
      "role": "member"
    }
  }
}

2. 页面停留事件 (page_leave)

记录用户在页面停留的时长,在路由变化或关闭页面时触发:

{
  "eventName": "page_leave",
  "properties": {
    "url": "https://example.com/#/home",
    "hash": "#/home",
    "title": "首页",
    "stayTime": 25000,
    "timestamp": 1647123456789
  }
}

3. 元素点击事件 (element_click)

智能捕获用户点击的可交互元素:

{
  "eventName": "element_click",
  "properties": {
    "elementId": "submit-btn",
    "elementClass": "btn btn-primary",
    "elementTag": "BUTTON",
    "elementText": "提交订单",
    "elementPath": "div.container > form > button#submit-btn",
    "x": 450,
    "y": 280,
    "url": "https://example.com/#/checkout",
    "hash": "#/checkout",
    "timestamp": 1647123456789
  }
}

4. 接口请求事件 (xhr_request)

监控AJAX请求的性能和状态:

{
  "eventName": "xhr_request",
  "properties": {
    "url": "https://api.example.com/v1/orders",
    "method": "POST",
    "status": 200,
    "duration": 237,
    "timestamp": 1647123456789
  }
}

5. JavaScript错误 (js_error)

捕获页面JavaScript运行时错误:

{
  "eventName": "js_error",
  "properties": {
    "message": "Cannot read property 'data' of undefined",
    "filename": "app.js",
    "lineno": 42,
    "colno": 15,
    "error": "TypeError: Cannot read property 'data' of undefined\n    at getData (app.js:42:15)...",
    "timestamp": 1647123456789
  }
}

6. Promise错误 (promise_error)

捕获未处理的Promise异常:

{
  "eventName": "promise_error",
  "properties": {
    "message": "Request failed with status code 404",
    "stack": "Error: Request failed with status code 404\n    at createError (axios.js:123:15)...",
    "timestamp": 1647123456789
  }
}

7. 用户登录事件 (user_login)

用户身份识别或变更时触发:

{
  "eventName": "user_login",
  "properties": {
    "userId": "user123",
    "username": "张三",
    "role": "member",
    "timestamp": 1647123456789
  }
}

数据上报机制

OnTrack SDK 使用高可靠的图片传输机制(Image Beacon)进行数据上报:

https://your-api-endpoint.com/collect?data={encoded-data}&_t=1647123456789

相比传统的 AJAX 和 fetch 方式,图片上报有以下优势:

  1. 更可靠的页面关闭处理:浏览器会自动完成图片请求,即使页面正在关闭
  2. 绕过跨域限制:不受同源策略影响,不需要服务器设置 CORS
  3. 兼容性更好:几乎所有浏览器都支持
  4. 防止阻塞页面:不阻塞页面主线程

页面关闭时会按优先级尝试以下上报方式:

  1. 优先使用 navigator.sendBeacon(最新浏览器支持)
  2. 次选同步 XHR 请求
  3. 最后使用图片请求作为保底方案

服务器接口要求

服务器需要支持接收 GET 请求数据,数据结构如下:

{
  "appId": "your-app-id",
  "events": [
    {
      "eventName": "page_view",
      "properties": {
        "url": "https://example.com",
        "timestamp": 1647123456789,
        ...
      }
    },
    ...
  ],
  "user": {
    "userId": "user123",
    "username": "张三",
    "role": "member"
  },
  "timestamp": 1647123456789,
  "sdk": "OnTrack",
  "sdkVersion": "1.0.0"
}

Vue集成最佳实践

Vue3项目中使用

main.js 中初始化:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { OnTrack } from 'OnTrack-sdk'

const app = createApp(App)

OnTrack.init({
  appId: import.meta.env.VITE_APP_ID,
  serverUrl: import.meta.env.VITE_TRACKING_URL,
  autoTrack: true
})

// 在路由钩子中管理用户登录状态
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    // 检查用户登录状态并设置用户信息
    const user = localStorage.getItem('user')
    if (user) {
      OnTrack.setUser(JSON.parse(user))
    }
  }
  next()
})

app.use(router).mount('#app')

组件中手动埋点

<template>
  <button @click="checkout">购买课程</button>
</template>

<script setup>
import { OnTrack } from 'OnTrack-sdk'

function checkout() {
  // 业务逻辑
  // ...
  
  // 手动埋点
  OnTrack.track({
    eventName: 'course_purchase',
    properties: {
      courseId: props.course.id,
      courseName: props.course.name,
      price: props.course.price,
    }
  })
}
</script>

数据安全

SDK内置了以下数据安全机制:

  1. 敏感信息过滤:自动过滤密码、token等敏感信息
  2. 数据本地存储加密:使用localStorage存储数据时进行简单加密
  3. 批量处理限制:单次上报的数据量和频率限制,避免服务器压力

浏览器兼容性

SDK支持所有现代浏览器,包括:

  • Chrome 60+
  • Firefox 55+
  • Safari 11+
  • Edge 15+
  • iOS Safari 11+
  • Android Chrome 60+

性能影响

SDK设计时充分考虑了性能影响:

  • 异步事件处理和上报
  • 批量处理减少请求数
  • 事件节流防止频繁触发
  • 最小化DOM操作
  • 图片上报方式轻量高效

贡献指南

欢迎贡献代码或提交问题:

  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 开启Pull Request

许可证

MIT