如何用网页脚本追踪用户

  • 点击埋点:当用户点击元素时,收集该点击元素上的信息,并返回给后端
  • 曝光埋点:当需要曝光元素在屏幕 🖥 上出现时,收集该元素上的信息,并返回给后端

数据收集

1
2
<button x-click="message" name="common">common button</button>
<div class="export" export-info="{}"></div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const pageClickInfo = {};
// 点击埋点
window.addEventListener("click", (event) => {
// 点击目标元素
const element = event.target;
const name = element.getAttribute("name");
// 信息收集 或 xhr...
name && (pageClickInfo[name] = element.getAttribute("x-click"));
});

// 曝光埋点
const intersectionObserver = new IntersectionObserver(
(entries) => {
entries.forEach((item) => {
console.log(item.target, item.intersectionRatio);
// 信息收集 或 xhr...
});
},
{ threshold: [0.5, 1] }
);
// 为需要曝光的元素添加
Array.from(document.getElementsByClassName("export")).forEach((el) => {
intersectionObserver.observe(el);
});

数据发送

通过 Beacon API

需要用到 Beacon API,用于发送不需要响应的 异步,非阻塞请求到服务器。

1
2
3
4
5
// 通常埋点数据实时发送,unload 方法用于记录用户停留在网页的时间
window.addEventListener("unload", function (event) {
//只能是 POST 请求 @params { url: string, data: ArrayBuffer、ArrayBufferView、Blob、DOMString、FormData 或 URLSearchParams }
navigator.sendBeacon("/log", "foo=bar");
});

通过 a 标签的 ping 属性

虽然发送的是 POST 请求,但只能发送 query 类型数据,不可指定 body

1
2
3
<a href="https://baidu.com" ping="/log?foo=bar">
click
</a>

反弹追踪

就是网页跳转时,先跳到一个或多个中间网址,以便收集信息,然后再跳转到原来的目标网址。
防止截取 UA 信息 以确保用户隐私信息,经常会在 【百度搜索】和【洋葱浏览器】上见到

1
2
3
4
5
6
7
8
// <a id="target" href="https://baidu.com">click</a>
const link = document.getElementById("target");

link.addEventListener("click", function (event) {
event.preventDefault();
const href = link.getAttribute("href");
window.location.href = `/go?raw_href=${encodeURIComponent(href)}`;
});
作者

Huasun47

发布于

2020-02-26

更新于

2020-02-26

许可协议