Barcode Detection API 在 Chrome 87+ 安全上下文中可用,需显式指定 formats(如["qr_code"]),detect()仅接受video/canvas/ImageBitmap,返回结果含rawValue、format和boundingBox,但无纠错信息。

Barcode Detection API 在 Chrome 中是否可用
目前(2024 年中),BarcodeDetection API 仅在 Chromium 内核浏览器(Chrome ≥ 87、Edge ≥ 87)的 安全上下文(HTTPS 或 localhost)中可用,且需用户主动授予摄像头权限。Safari 和 Firefox 完全不支持该 API,调用 typeof BarcodeDetection 会返回 "undefined"。
如何正确初始化 BarcodeDetector 实例
不能直接 new BarcodeDetection() —— 构造函数必须传入 {formats: [...]} 显式指定要识别的码制,否则会抛出 TypeError: Failed to construct 'BarcodeDetection': format list must not be empty。
常用格式包括:"qr_code"、"ean_13"、"code_128"。二维码请务必写成 "qr_code"(不是 "qrcode" 或 "QR_CODE"):
const detector = new BarcodeDetection({
formats: ["qr_code"] // ✅ 正确
});如果需要多码制,可传数组:["qr_code", "ean_13", "code_128"]。注意:格式越多,检测延迟略增,移动端尤其明显。
立即学习“前端免费学习笔记(深入)”;
为什么 detect() 总是返回空数组或报错
常见原因有三个:
-
detect()输入必须是<video>元素、<canvas>或ImageBitmap,不能传<img>或 base64 字符串 —— 否则报NotAllowedError或静默失败 - 视频流未播放(
video.play()未调用或被阻止)、或视频帧为空(video.readyState < 2),会导致detect()拒绝执行 - 检测区域太小或模糊:二维码边长建议 ≥ 120px(在 canvas 上绘制后),且需保证对焦与光照;
BarcodeDetection不做图像增强,低质量输入基本无法识别
推荐做法:监听 video 的 canplay 事件后再首次调用 detector.detect(video),并用 requestAnimationFrame 节流(避免每帧都检):
video.addEventListener("canplay", () => {
detectLoop();
});
async function detectLoop() {
if (video.readyState === video.HAVE_ENOUGH_DATA) {
const results = await detector.detect(video);
if (results.length > 0) console.log(results[0].rawValue);
}
requestAnimationFrame(detectLoop);
}识别结果中的关键字段和常见陷阱
detect() 返回的是 BarcodeDetectionResult[] 数组,每个对象含:
-
rawValue:解码后的字符串(如"https://example.com"),对二维码必有值;但条形码可能为null(如仅检测到位置未成功解码) -
format:字符串,值为"qr_code"等,注意大小写固定,不可用于switch时写错 -
boundingBox:DOMRectReadOnly,坐标基于 canvas 像素,**不是 CSS 像素** —— 若 canvas 用了width/height与style.width/style.height不一致的缩放,需手动换算
特别注意:BarcodeDetection 不提供纠错等级、掩码模式等 QR 码元信息,也无法区分同一画面多个二维码(它只返回所有检测到的结果,无层级或顺序保证)。
实际项目中,频繁调用 detect() 可能触发 CPU 升高,建议加防抖(如两次成功识别间隔 try/catch 包裹异步调用 —— 权限被拒、设备断开等都会抛出异常。



















