【前端埋点】uniapp小程序自动化埋点方案

2025/05/15 12:09:402025/03/11 12:03:40

本文选择了监听全局事件的方式实现了 uniapp 小程序的埋点,对业务的侵入性较小。

代码位置

https://gitee.com/zhangkb/example-code/tree/master/uniapp-trackopen in new window

整体架构设计

整个 Tracker 类的设计与网站埋点open in new window方案一致,只是针对小程序做了适配,这里不再赘述。

uniapp 中如何监听全局事件

GlobalEventProxy.js

通过劫持 Component 的形式实现监听,具体思路看这篇文章:Uniapp 微信小程序实现全局事件监听并进行数据埋点的方法open in new window

import { TrackEvent } from "./Tracker";
(function () {
  const isObject = function (obj) {
    if (obj === undefined || obj === null) {
      return false;
    } else {
      return toString.call(obj) == "[object Object]";
    }
  };
  // 劫持Component
  const _componentProto_ = Component;
  Component = function (options) {
    //options.methods内有uniapp注入的事件处理器__e及mpHook
    Object.keys(options.methods).forEach((methodName) => {
      if (methodName == "__e") {
        //劫持事件处理器
        eventProxy(options.methods, methodName);
      }
    });
    _componentProto_.apply(this, arguments);
  };

  function eventProxy(methodList, methodName) {
    const _funcProto_ = methodList[methodName];
    methodList[methodName] = function () {
      _funcProto_.apply(this, arguments);

      try {
        if (isObject(arguments[0])) {
          if (Object.keys(arguments[0]).length > 0) {
            //记录触发页面信息
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            const currentPageVm = currentPage.$vm;
            // const type = arguments[0]['type']
            const currentTarget = arguments[0].currentTarget || {};
            const dataset = currentTarget.dataset || {};
            // console.log(999999, dataset, arguments[0])

            if (currentPageVm.tracker) {
              if (dataset[TrackEvent.click]) {
                currentPageVm.tracker.handleClick(dataset);
              }
            }
          }
        }
      } catch (e) {
        console.error("track proxy error", e);
      }
    };
  }
})();

main.js

src/main.js 中引入 GlobalEventProxy.js

import "@/services/bussiness/track/GlobalEventProxy";
import Vue from "vue";
import App from "@/App.vue";

Vue.config.productionTip = false;

const app = new Vue({
  ...App,
});

app.$mount();

参考

uni-app 下微信小程序自动埋点open in new window

GrowingIO 小程序采集 SDKopen in new window

前端组件化埋点的实践open in new window

Uniapp 微信小程序实现全局事件监听并进行数据埋点的方法open in new window

浅谈前端埋点 & 监控open in new window

前端埋点实现方案 ✔open in new window

浅析前端监控与埋点open in new window

微信小程序《埋点系统设计》open in new window

微信小程序无埋点数据采集方案open in new window

微信小程序组件化埋点实践open in new window