【前端埋点】纯前端实现 A/B Test

发布于:2025-09-09 ⋅ 阅读:(24) ⋅ 点赞:(0)

“纯前端实现 A/B Test”,意思就是 没有后端分流、也不依赖流量网关,那么只能靠前端逻辑来做“流量切分”。


🎯 目标

  • 80% 的用户 → A 页面
  • 20% 的用户 → B 页面
  • 且要保证 同一个用户每次访问结果一致(否则用户刷新页面时 A/B 会跳来跳去,没意义)。

✅ 实现思路

方法一:基于随机数 + 本地存储(推荐)

function assignABTest() {
  // 先看本地是否已有分组结果
  let group = localStorage.getItem('ab_group')
  if (!group) {
    // 随机生成一个 [0,1) 的数
    const rand = Math.random()
    // 按比例分配
    group = rand < 0.8 ? 'A' : 'B'
    localStorage.setItem('ab_group', group)
  }
  return group
}

// 使用
const group = assignABTest()
if (group === 'A') {
  window.location.href = '/pageA.html'
} else {
  window.location.href = '/pageB.html'
}

👉 特点:

  • 第一次访问时随机分配。
  • 后续访问保持一致(因为结果存了 localStorage)。
  • 不需要后端,不需要流量标识。

方法二:基于用户特征(比如 UA / IP Hash)

如果你不想依赖 localStorage(例如用户清理缓存后可能变化),可以用一些用户环境特征来算哈希值:

function hashCode(str) {
  let hash = 0
  for (let i = 0; i < str.length; i++) {
    hash = (hash << 5) - hash + str.charCodeAt(i)
    hash |= 0
  }
  return Math.abs(hash)
}

function assignABTestByUA() {
  const ua = navigator.userAgent
  const hash = hashCode(ua)
  const ratio = hash % 100 // 映射到 0-99
  return ratio < 80 ? 'A' : 'B'
}

👉 特点:

  • 同一设备 UA → 分组稳定。
  • 但不同浏览器、换设备就会变组。

方法三:基于 Cookie(和 localStorage 类似)

function getCookie(name) {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'))
  return match ? match[2] : null
}

function setCookie(name, value, days) {
  const d = new Date()
  d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000)
  document.cookie = `${name}=${value};expires=${d.toUTCString()};path=/`
}

function assignABTest() {
  let group = getCookie('ab_group')
  if (!group) {
    group = Math.random() < 0.8 ? 'A' : 'B'
    setCookie('ab_group', group, 30) // 保存30天
  }
  return group
}

👉 特点:

  • 可以跨刷新稳定,甚至跨子页面。
  • 但 cookie 会随请求发给后端,不太纯粹。

网站公告

今日签到

点亮在社区的每一天
去签到