本文所说的埋点上报,只包含两种:点击上报(click)、曝光上报(show)。
整体思路:
点击上报: 使用 window.addEventListener('click')
做全局点击的代理。
曝光上报:
- 使用
IntersectionObserver
监听dom元素是否出现在可视区域内。 - 使用
window.MutationObserver
监听全局的dom元素增减状态,以便在dom初始化时,挂载IntersectionObserver
监听事件
埋点核心代码
bury.js
export default class Bury {
constructor(option) {
const { click = () => {}, show = () => {} } = option;
this.click = click;
this.show = show;
this.obServerList = [];
this.init();
}
init() {
window.addEventListener('click', this.getClickBury.bind(this), true);
// Firefox和Chrome早期版本中带有前缀
const MutationObserver =
window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
// 创建观察者对象
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
for (let currentNode of mutation.addedNodes) {
// 获取添加的节点
if (currentNode.nodeType !== 1) continue;
//查看节点自身是否有曝光埋点,然后添加曝光监听
this.bindShow(currentNode);
//获取当前节点的后代曝光节点
const childrenShowList = Array.from(currentNode.querySelectorAll('[data-bury]'));
//后代添加曝光监听
childrenShowList.forEach((item) => {
this.bindShow(item);
});
}
});
});
// 传入目标节点和观察选项
observer.observe(document.getElementsByTagName('body')[0], { childList: true, subtree: true });
}
getClickBury(e) {
let target = e.target;
while (target) {
const tagName = target.tagName || '';
if (tagName.toLowerCase() === 'html') break;
const bury = (target.dataset || {}).bury;
if (bury && bury !== 'false') {
// 处理一个元素触发多个埋点的情况
const dataMap = bury.split('||');
for (const item of dataMap) {
const [buryType, buryData] = item.split(':');
if (buryType !== 'click') continue;
this.click(buryData);
}
}
target = target.parentNode;
}
}
bindShow(ele) {
const bury = (ele.dataset || {}).bury;
if (bury) {
// 处理一个元素触发多个埋点的情况
const dataMap = bury.split('||');
for (const item of dataMap) {
const [buryType] = item.split(':');
//如有有曝光标示,监听后直接返回
if (buryType === 'show') {
return this.obServerView(ele);
}
}
}
}
getShowBury(ele) {
const bury = (ele.dataset || {}).bury;
if (bury && bury !== 'false') {
// 处理一个元素触发多个埋点的情况
const dataMap = bury.split('||');
for (const item of dataMap) {
const [buryType, buryData] = item.split(':');
if (buryType !== 'show') continue;
this.show(buryData);
}
}
}
obServerView(ele, __key__) {
if (!ele) return;
// 阻止重复注册ref,导致多次观测
const key = __key__ || ele;
if (this.obServerList.indexOf(key) > -1) return;
this.obServerList.push(key);
const io = new IntersectionObserver(
(entries) => {
// 有些移动端机型,尤其android机型, 会达不到1的阈值,所以这里设置成了0.8。
// threshold: 0.8 设置成0.8
if (entries[0].intersectionRatio >= 0.8) {
this.getShowBury(ele);
this.obServerList.filter((item) => item !== ele);
io.unobserve(ele);
}
},
{
threshold: 0.8,
},
);
io.observe(ele);
}
}
实例化时机
无论vue还是react,一定要在入口文件优先注册这个类的实例。
react 的 index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App.js'
import Bury from './bury.js'
//埋点相关
new Bury({
click(data) {
console.log(data);
},
show(data) {
console.log(data);
},
});
ReactDOM.render(
<App />,
document.getElementById('root')
)
Vue 的 main.js
import { createApp } from 'vue'
import App from './App.vue'
import Bury from './bury.js'
//埋点相关
new Bury({
click(data) {
console.log(data);
},
show(data) {
console.log(data);
},
});
createApp(App).mount('#app')
使用时机
现在给一个按钮添加点击和曝光的埋点,
点击的时候上报 {a:1,b:2}
曝光的时候上报 {c:3,d:4}
写法如下:
<Button
data-bury={`click:${JSON.stringify({a:1,b:2})}||show:${JSON.stringify({c:3,d:4})}`}
>
点击
</Button>;
在入口文件中吐出数据。
new Bury({
click(data) {
console.log(JSON.parse(data)); // {a:1,b:2}
},
show(data) {
console.log(JSON.parse(data)); // {c:3,d:4}
},
});