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

max-gtm-sdk

v3.0.0

Published

一个功能强大的 Google Tag Manager SDK,支持事件跟踪、页面统计、广告追踪等功能

Readme

Max GTM SDK

一个现代化的 Google Tag Manager SDK,专为可靠的数据追踪而设计。支持事件追踪、广告监控、IP获取等功能,具有完善的错误处理和重试机制。

✨ 功能特点

  • 🚀 非阻塞架构: IP获取不会阻塞事件上报
  • 🔄 智能重试机制: 失败事件自动重新入队并重试
  • 📦 批量处理: 高效的事件批量上报
  • 🎯 广告追踪: 自动监控广告填充和曝光
  • 📱 页面卸载处理: 使用多种策略确保数据不丢失
  • 🛡️ 错误容错: 完善的错误处理和超时控制
  • 🔧 模块化设计: 清晰的代码结构,易于维护和扩展
  • 🐛 调试友好: 详细的调试日志和状态监控

📦 安装

npm install max-gtm-sdk

🚀 快速开始

基础配置

import { GTMSDK } from 'max-gtm-sdk';

const gtm = new GTMSDK({
    debug: true,                    // 开启调试模式
    showIp: true,                   // 启用IP追踪
    ipApiUrl: 'https://api.example.com/ip',  // IP获取API
    beaconUrl: 'https://api.example.com/beacon', // 页面卸载时的上报地址
    batchSize: 10,                  // 批量处理大小
    retryTimes: 3,                  // 重试次数
    retryDelay: 1000               // 重试延迟(ms)
});

页面浏览追踪

// 基础页面浏览
await gtm.pageView();

// 带自定义参数的页面浏览
await gtm.pageView({
    page_category: 'product',
    page_type: 'detail',
    product_id: '12345'
});

事件追踪

// 点击事件
await gtm.click({
    element: 'buy-button',
    text: '立即购买',
    position: { x: 100, y: 200 }
});

// 自定义事件
await gtm.customEvent('purchase', {
    action_id: 'purchase',
    action_desc: '用户购买',
    product_id: '12345',
    price: 99.99,
    currency: 'CNY'
});

// 批量事件
gtm.batchTrack([
    {
        event: 'add_to_cart',
        params: { product_id: '12345', quantity: 1 }
    },
    {
        event: 'view_item',
        params: { product_id: '12345', category: 'electronics' }
    }
]);

🎯 广告追踪

SDK 提供自动化的广告追踪功能:

// 监控广告位
const adElement = document.getElementById('ad-banner');
gtm.observeAdSlot('ad-banner', adElement);

// SDK 会自动追踪:
// - mx_ad_fill: 广告填充事件
// - mx_ad_impression: 广告曝光事件(50%可见时触发)

🔧 高级功能

队列管理

// 获取队列状态
const status = gtm.getQueueStatus();
console.log(status);
// {
//   queueLength: 5,
//   isProcessing: false,
//   retryCount: 0,
//   hasIp: true,
//   ipPromisePending: false
// }

// 手动刷新队列
gtm.flush();

// 清理资源
gtm.destroy();

IP 追踪配置

const gtm = new GTMSDK({
    showIp: true,
    ipApiUrl: 'https://your-api.com/ip',
    // IP API 应返回格式: { code: 200, ip: "1.2.3.4", requestedWith: "..." }
});

// 所有事件将自动包含 u_ip 字段

页面卸载处理

SDK 自动处理页面卸载场景:

const gtm = new GTMSDK({
    beaconUrl: 'https://api.example.com/beacon'  // 可选:使用 sendBeacon
});

// 监听以下事件自动刷新队列:
// - visibilitychange (页面隐藏)
// - beforeunload (页面卸载)
// - pagehide (移动端页面隐藏)

🏗️ 架构设计

SDK 采用模块化设计:

src/
├── core/
│   ├── GTMSDK.js          # 主SDK类
│   ├── IpTracker.js       # IP追踪模块
│   ├── EventQueue.js      # 事件队列管理
│   ├── AdTracker.js       # 广告追踪模块
│   └── UnloadTracker.js   # 页面卸载处理
├── utils/                 # 工具函数
└── index.js              # 入口文件

模块说明

  • GTMSDK: 主入口类,协调各个模块
  • IpTracker: 处理IP获取,支持超时和错误处理
  • EventQueue: 管理事件队列,支持批量处理和重试
  • AdTracker: 广告监控,使用 IntersectionObserver 和 MutationObserver
  • UnloadTracker: 页面卸载时的数据保护

🧪 测试

项目包含完整的测试页面:

# 构建项目
npm run build

# 在浏览器中打开 test.html
open test.html

测试页面功能:

  • ✅ SDK 初始化和配置
  • ✅ 各种事件追踪测试
  • ✅ 广告追踪演示
  • ✅ 实时 DataLayer 监控
  • ✅ 控制台日志捕获
  • ✅ 队列状态监控

📊 事件数据格式

标准事件字段

所有事件都包含以下标准字段:

{
    event: "event_name",           // 事件名称
    timestamp: "2024-01-01T00:00:00.000Z",  // 时间戳
    u_ip: "1.2.3.4",             // 用户IP(如果启用)
    // ... 其他自定义参数
}

页面浏览事件 (in_page)

{
    event: "in_page",
    page_path: "/current/path",
    page_title: "页面标题",
    page_url: "https://example.com/current/path",
    page_referrer: "https://example.com/previous",
    device_info: "{...}",          // 设备信息JSON字符串
    // ... 自定义参数
}

广告事件

// 广告填充
{
    event: "mx_ad_fill",
    action_id: "mx_ad_fill",
    action_desc: "ad_fill",
    ad_id: "ad-banner-1",
    ad_position: "top",            // top/middle/bottom
    extra: {
        page_path: "/current/path",
        page_title: "页面标题"
    }
}

// 广告曝光
{
    event: "mx_ad_impression",
    action_id: "mx_ad_impression",
    action_desc: "ad_impression",
    ad_id: "ad-banner-1",
    ad_position: "top",
    extra: {
        page_path: "/current/path",
        page_title: "页面标题"
    }
}

⚠️ 注意事项

  1. 异步操作: 所有追踪方法都是异步的,建议使用 async/await
  2. IP 获取: IP 获取有5秒超时限制,不会阻塞事件上报
  3. 批量处理: 大量事件会自动进入队列批量处理
  4. 错误处理: 失败的事件会自动重试,超过重试次数后丢弃
  5. 页面卸载: 页面卸载时会自动刷新待发送事件
  6. 浏览器兼容性: 需要支持 ES6+ 的现代浏览器

🔧 开发

# 安装依赖
npm install

# 开发模式
npm run dev

# 构建
npm run build

# 测试
npm test

📝 更新日志

v0.0.2

  • ✅ 重构为模块化架构
  • ✅ 修复IP获取阻塞问题
  • ✅ 改进重试机制
  • ✅ 添加页面卸载处理
  • ✅ 移除页面停留时长功能(使用GA4内置)
  • ✅ 完善错误处理和调试功能

v0.0.1

  • 🎉 初始版本发布

📄 许可证

MIT License

🤝 贡献

欢迎提交 Issue 和 Pull Request!


Made with ❤️ by Johan