Yasin

Yasin

网页获取用户信息的方式

网页获取用户信息的方式


1. 浏览器原生 API

Navigator 信息

// 浏览器和设备信息
navigator.userAgent; // 浏览器标识(Chrome/Firefox/Safari...)
navigator.language; // 语言(zh-CN)
navigator.platform; // 操作系统(Win32/MacIntel)
navigator.onLine; // 是否联网
navigator.hardwareConcurrency; // CPU 核心数
navigator.deviceMemory; // 设备内存(GB)
navigator.connection; // 网络类型(4g/wifi)

屏幕信息

screen.width; // 屏幕宽度
screen.height; // 屏幕高度
window.devicePixelRatio; // 设备像素比

地理位置(需要用户授权)

navigator.geolocation.getCurrentPosition(
  (pos) => {
    console.log(pos.coords.latitude); // 纬度
    console.log(pos.coords.longitude); // 经度
  },
  (err) => console.log("用户拒绝了"),
);
// 浏览器会弹出授权弹窗,用户可以拒绝

摄像头 / 麦克风(需要用户授权)

navigator.mediaDevices
  .getUserMedia({ video: true, audio: true })
  .then((stream) => {
    /* 获取到摄像头流 */
  })
  .catch((err) => {
    /* 用户拒绝 */
  });

2. Cookie

// 设置
document.cookie = "userId=123; max-age=86400; path=/";

// 读取
document.cookie; // 'userId=123; theme=dark'

// 后端也可以通过 Set-Cookie 设置
// HTTP 响应头:Set-Cookie: sessionId=abc; HttpOnly; Secure

特点:

  • 每次 HTTP 请求自动携带
  • 可设置 HttpOnly(JS 不可读,防 XSS)
  • 可设置 Secure(仅 HTTPS 传输)
  • 跨站限制由 SameSite 控制

3. 本地存储

// localStorage(永久存储,同源共享)
localStorage.setItem("token", "xxx");
localStorage.getItem("token");

// sessionStorage(标签页关闭即清除)
sessionStorage.setItem("temp", "xxx");

// IndexedDB(大量结构化数据)
const request = indexedDB.open("myDB", 1);

4. 用户行为追踪

点击 / 滚动 / 停留时间

// 点击追踪
document.addEventListener('click', (e) => {
  const target = e.target as HTMLElement;
  report({
    type: 'click',
    tagName: target.tagName,
    text: target.innerText?.slice(0, 50),
    x: e.clientX,
    y: e.clientY,
    timestamp: Date.now(),
  });
});

// 页面停留时间
const enterTime = Date.now();
window.addEventListener('beforeunload', () => {
  report({
    type: 'stay-time',
    duration: Date.now() - enterTime,
  });
});

// 滚动深度
window.addEventListener('scroll', () => {
  const scrollPercent = Math.round(
    (window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100
  );
  report({ type: 'scroll-depth', value: scrollPercent });
});

5. 浏览器指纹

不用 Cookie,也能识别用户(精确率 90%+):

// 组合多种信息生成唯一指纹
const fingerprint = {
  userAgent: navigator.userAgent,
  language: navigator.language,
  screenResolution: `${screen.width}x${screen.height}`,
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  plugins: [...navigator.plugins].map(p => p.name),
  canvas: getCanvasFingerprint(),    // Canvas 渲染差异
  webgl: getWebGLFingerprint(),      // WebGL 渲染差异
  fonts: getInstalledFonts(),        // 已安装字体
  hardwareConcurrency: navigator.hardwareConcurrency,
};

// Canvas 指纹:不同设备渲染同一内容,像素级别有差异
function getCanvasFingerprint() {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d')!;
  ctx.fillText('fingerprint', 10, 10);
  return canvas.toDataURL(); // 不同设备生成的 dataURL 不同
}

常用库:FingerprintJS


6. 第三方跟踪

埋点 SDK

<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_ID"></script>
<script>
  gtag("config", "GA_ID");
  // 自动收集:PV、来源、设备、地区、停留时间...
</script>

<!-- 百度统计 -->
<script>
  var _hmt = _hmt || [];
  (function () {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?xxx";
    document.head.appendChild(hm);
  })();
</script>

跟踪像素(1x1 透明图片)

<!-- 邮件/页面打开时触发请求,服务端记录 -->
<img
  src="https://track.example.com/pixel.gif?userId=123&page=home"
  width="1"
  height="1"
/>

7. 登录后获取(主动提供)

// 用户登录后,后端返回用户信息
const res = await fetch("/api/user/profile", {
  headers: { Authorization: `Bearer ${token}` },
});

const user = await res.json();
// { name, email, phone, avatar, ... }

获取方式分类

方式 是否需要授权 获取内容
navigator 设备、浏览器、网络
Cookie 会话标识、偏好
localStorage 本地存储的任意数据
地理位置 ✅ 弹窗授权 经纬度
摄像头/麦克风 ✅ 弹窗授权 音视频流
浏览器指纹 设备唯一标识
行为追踪 点击、滚动、停留
登录接口 ✅ 用户主动 姓名、邮箱、手机号