You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Barcode Detection API调用时rawData返回undefined的解决方法

Barcode Detection API检测结果rawData属性为undefined问题修复

问题场景

在个人网站集成二维码检测功能时,选用Barcode Detection API开发,实际调用检测接口后,返回结果的rawData属性值始终为undefined,无法正常获取解析到的条码内容。

问题复现代码

HTML结构

<meta name="viewport" content="width=device-width"/>
<video id="bar" autoplay style="width:100vw;height:100vh;margin:0;object-fit:cover;"></video>
<canvas id="canvas1" hidden></canvas>
<img id="input" hidden/>

JS业务逻辑

navigator.mediaDevices.getUserMedia({
    audio: 0,
    video: {
        facingMode: {
            exact: "environment"
        }
    }
}).then(s => {
    const bar = document.getElementById('bar');
    bar.srcObject = s;
    bar.onloadedmetadata = () => {
        setInterval(() => {
            const canvas = document.getElementById('canvas1');
            canvas.width = bar.videoWidth;
            canvas.height = bar.videoHeight;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(bar, 0, 0);
            const input = document.getElementById('input');
            input.src = canvas.toDataURL();
            if ('BarcodeDetector' in window) {
                const detector = new BarcodeDetector();
                detector.detect(input).then(detections => {
                    detections.forEach(detected => {
                        alert(detected.rawData)
                    })
                })
            }
        }, -1)
    }
});

运行效果

Barcode Detection API运行输出

修复方案

问题由属性名使用错误导致:Barcode Detection API正式标准中,存储条码解析结果的属性为rawValue,rawData是早期草案/旧版本浏览器实现使用的非标准属性名,因此在新版本浏览器环境下读取rawData会返回undefined。
兼容新旧版本浏览器的读取写法如下:

alert(detected.rawValue || detected.rawData);

内容的提问来源于stack exchange,提问作者HEMANTH ABHIRAM SOMARAJU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 09:39:42