【前端埋点】uniapp小程序自动化埋点方案
2025/05/15 12:09:402025/03/11 12:03:40
本文选择了监听全局事件的方式实现了 uniapp 小程序的埋点,对业务的侵入性较小。
代码位置
https://gitee.com/zhangkb/example-code/tree/master/uniapp-track
整体架构设计
整个 Tracker
类的设计与网站埋点方案一致,只是针对小程序做了适配,这里不再赘述。
uniapp 中如何监听全局事件
GlobalEventProxy.js
通过劫持 Component
的形式实现监听,具体思路看这篇文章:Uniapp 微信小程序实现全局事件监听并进行数据埋点的方法。
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();