Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to use JavaScript Barcode Detection API

Programming Bytes

The Barcode Detection API detects linear and 2D barcodes in images.

Check if the browser supports BarcodeDetector

if ( 'BarcodeDetector' in window ) {
  console.log('Barcode Detector supported!');
}else {
    console.log('Barcode Detector is not supported in this browser');
}

Creating a barcode detector

To detect a barcode, we need a BarcodeDetector object that can pass an array of formats we want to scan for. If we only want to scan the QRCode, we can pass qr_code only. Not all formats will be supported on all platforms.

const barcodeDetector = new BarcodeDetector({
  formats: [
    'aztec',
    'code_128',
    'code_39',
    'code_93',
    'codabar',
    'data_matrix',
    'ean_13',
    'ean_8',
    'itf',
    'pdf417',
    'qr_code',
    'upc_a',
    'upc_e'
  ]
});

List format that can be detected

Before passing the desired format to the BarcodeDetector, we can check if the format is supported by the browser by calling getSupportedFormats, which will return a promise. Upon resolving the promise, we will get an array containing formats that can be detected by the browser.

async function checkIfFormatIsSupported(format) {
 
   return await BarcodeDetector.getSupportedFormats()
          .then(supportedFormats => {
              console.log(supportedFormats);
              return supportedFormats.indexOf(format) !== -1;
          });
}

Refer to the supported formats here.

Detect the barcode

We can detect the barcode by calling the detect() method, which takes an image object. The image object can be an element, Blob, ImageData, or CanvasImageSource.

try {
  const barcodes = await barcodeDetector.detect(image);
  barcodes.forEach(barcode => console.log(barcode));
} catch (e) {
 // if the imageElement is invalid, the DOMException will be thrown
  console.error('Barcode detection failed:', e);
}

The detect method will return a promise, upon resolving this promise, we will get the detected barcode list. Each barcode has a:

  • format – the detected format of the Barcode
  • boundingBox – contains the coordinates of the Barcode
  • rawData – actual value present in the Bar Code
  • cornerPoints – leftTop , rightTop, rightBottom, and leftBottom.

You can see a working example here and see how to detect a barcode from the webcam here.

Summary

  • The Barcode Detection API detects linear and 2D barcodes in images.
  • The detect method in the BarcodeDetector is used to detect the barcode.
  • This feature is available only in secure contexts (HTTPS).
  • This feature is available in Web worker.

Browser support

supported browsers

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring