本文所說的埋點上報,只包含兩種:點擊上報(click)、曝光上報(show)。
整體思路:
點擊上報: 使用 window.addEventListener('click')
做全局點擊的代理。
曝光上報:
- 使用
IntersectionObserver
監(jiān)聽dom元素是否出現(xiàn)在可視區(qū)域內(nèi)。 - 使用
window.MutationObserver
監(jiān)聽全局的dom元素增減狀態(tài),以便在dom初始化時,掛載IntersectionObserver
監(jiān)聽事件
埋點核心代碼
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;
// 創(chuàng)建觀察者對象
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
for (let currentNode of mutation.addedNodes) {
// 獲取添加的節(jié)點
if (currentNode.nodeType !== 1) continue;
//查看節(jié)點自身是否有曝光埋點,然后添加曝光監(jiān)聽
this.bindShow(currentNode);
//獲取當(dāng)前節(jié)點的后代曝光節(jié)點
const childrenShowList = Array.from(currentNode.querySelectorAll('[data-bury]'));
//后代添加曝光監(jiān)聽
childrenShowList.forEach((item) => {
this.bindShow(item);
});
}
});
});
// 傳入目標(biāo)節(jié)點和觀察選項
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') {
// 處理一個元素觸發(fā)多個埋點的情況
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) {
// 處理一個元素觸發(fā)多個埋點的情況
const dataMap = bury.split('||');
for (const item of dataMap) {
const [buryType] = item.split(':');
//如有有曝光標(biāo)示,監(jiān)聽后直接返回
if (buryType === 'show') {
return this.obServerView(ele);
}
}
}
}
getShowBury(ele) {
const bury = (ele.dataset || {}).bury;
if (bury && bury !== 'false') {
// 處理一個元素觸發(fā)多個埋點的情況
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;
// 阻止重復(fù)注冊ref,導(dǎo)致多次觀測
const key = __key__ || ele;
if (this.obServerList.indexOf(key) > -1) return;
this.obServerList.push(key);
const io = new IntersectionObserver(
(entries) => {
// 有些移動端機型,尤其android機型, 會達(dá)不到1的閾值,所以這里設(shè)置成了0.8。
// threshold: 0.8 設(shè)置成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,一定要在入口文件優(yōu)先注冊這個類的實例。
react 的 index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App.js'
import Bury from './bury.js'
//埋點相關(guān)
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'
//埋點相關(guān)
new Bury({
click(data) {
console.log(data);
},
show(data) {
console.log(data);
},
});
createApp(App).mount('#app')
使用時機
現(xiàn)在給一個按鈕添加點擊和曝光的埋點,
點擊的時候上報 {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>;
在入口文件中吐出數(shù)據(jù)。
new Bury({
click(data) {
console.log(JSON.parse(data)); // {a:1,b:2}
},
show(data) {
console.log(JSON.parse(data)); // {c:3,d:4}
},
});