什么是埋点?
埋点是一种用于跟踪用户在网站或应用中行为的数据采集技术,通过记录点击、浏览等操作,帮助团队进行用户行为分析、AB 实验、错误监听,指导优化方向和资源分配
监控类型
基于要监控的内容,可以分为:数据监控、性能监控、异常监控
上报方式
手动上报
- 在用户点击某个按钮时,开发者会在按钮的点击事件中调用埋点上报函数,如:
button.addEventListener('click', () => { sendEvent('click_button', { userId: '12345', time: Date.now() });
});
- 页面展示:在页面加载完成时,埋点记录页面的展示情况
window.addEventListener('load', () => { sendEvent('page_view', { page: 'homepage', time: Date.now() });
});
- 组件 DOM 超出 50% 曝光
const observer = new IntersectionObserver((entries) => {entries.forEach(entry => {if (entry.isIntersecting && entry.intersectionRatio > 0.5) {sendEvent('component_exposure', { component: 'banner', time: Date.now() });}});}, {threshold: [0.5] // 超过50%可见时触发});
const component = document.querySelector('#banner');observer.observe(component);
- 自动上报(无埋点)
使用一些埋点平台(如百度统计、 GrowingIO、神策数据等),业务人员可以在后台系统的可视化界面上点击页面元素,配置该元素的埋点逻辑。系统会自动捕获该元素的操作,并将数据上报至服务器
百度统计举例:
网站:https://tongji.baidu.com/web5/welcome/login
添加埋点代码
https://tongji.baidu.com/main/setting/10000554972/home/site/getjs
vue项目中在main.js中添加
(function () {const hm = document.createElement("script");hm.src = "https://hm.baidu.com/hm.js?3e10ff72349f84b8f223690xxxxx";const s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();router.beforeEach((to, from, next) => {if (_hmt) {if (to.path) {_hmt.push(["_trackPageview", "/#" + to.fullPath]);}}next();});
或者
<!DOCTYPE html>
<html lang=""><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1.0"><link rel="icon" href="<%= BASE_URL %>favicon.ico"><title><%= htmlWebpackPlugin.options.title %></title><script>const hostName = window.location.hostname.toLowerCase();// 判断正式环境才生效if (~hostName.indexOf('xxxxxxxxxx')){var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "https://hm.baidu.com/hm.js?xxxxxxxxxxxxxxxxxxxx";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();}</script></head><body><noscript><strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app"></div><!-- built files will be auto injected --></body>
</html>