背景与价值sendBeacon可在后台上报事件,但不当使用会造成资源消耗与隐私风险。统一采样与限制可提升治理。统一规范采样:默认采样比例如10%。大小:单次上报大小限制如64KB。速率:每分钟上限与队列化。核心实现采样与限制function sample(p = 0.1): boolean { return Math.random() < p } function withinSize(body: Blob | string | ArrayBuffer, max = 64 * 1024): boolean { if (typeof body === 'string') return new TextEncoder().encode(body).length <= max if (body instanceof Blob) return body.size <= max if (body instanceof ArrayBuffer) return body.byteLength <= max return false } class Rate { tokens = 0; cap = 60; last = Date.now(); refill(rpm = 60) { const now = Date.now(); const add = ((now - this.last) / 60000) * rpm; this.tokens = Math.min(this.cap, this.tokens + add); this.last = now } take(n = 1): boolean { this.refill(); if (this.tokens >= n) { this.tokens -= n; return true } return false } } class Queue { q: any[] = []; push(d: any) { this.q.push(d) } pop(): any | undefined { return this.q.shift() } len(): number { return this.q.length } } async function flush(endpoint: string, q: Queue, rate: Rate, p = 0.1) { while (q.len() > 0) { const d = q.pop()! if (!sample(p)) continue if (!withinSize(d)) continue if (!rate.take()) { await new Promise(r => setTimeout(r, 1000)); continue } try { navigator.sendBeacon(endpoint, d) } catch {} } } 落地建议对上报进行采样与大小/速率限制,并队列化处理,减少资源消耗与隐私风险。验证清单是否设置采样、大小与速率限制;队列是否按节奏发送。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
2.350776s