The Barcode Detection API detects linear and 2D barcodes in images.
if ( 'BarcodeDetector' in window ) {
console.log('Barcode Detector supported!');
}else {
console.log('Barcode Detector is not supported in this browser');
}
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'
]
});
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.
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:
You can see a working example here and see how to detect a barcode from the webcam here.
detect
method in the BarcodeDetector is used to detect the barcode.