微信小程序全局点击事件埋点

75 阅读1分钟

实现微信小程序中对点击事件的自动埋点功能,可用于统计用户行为数据。

核心功能介绍

该功能主要通过重写微信小程序的 Component 构造函数来实现全局点击事件监听:

const originalComponent = Component;
Component = function (componentConfig) {
  // ...
}
实现原理
  1. 拦截组件方法

    保存原始 Component 函数 遍历组件配置中的所有方法 (methods)

  2. 对每个方法进行包装处理

    识别点击事件 检测方法调用时的第一个参数是否为点击事件:


const newComponentConfig = { ...componentConfig };
if (newComponentConfig.methods) {
  Object.keys(newComponentConfig.methods).forEach((key) => {
      const method = newComponentConfig.methods[key];
      if (typeof method === "function") {
          newComponentConfig.methods[key] = function (...args) {
              const event = args[0];
              if (event && event.type && (event.type === "tap" || event.type === "touchend")) {
                 // 处理点击事件
                 .............
                 // 进行上报
                 .............
                 // 最后执行原始方法并保持正确的上下文和参数
                return method.apply(this, args);
               }
          }
      }
  }
}