Creating a Barcode Detector Using the Browser BarcodeDetector API
🤳

Creating a Barcode Detector Using the Browser BarcodeDetector API

Tags
Javascript
Computer Science
Video
Web Dev
Software Development
App Dev
Thought Experiments
Tech
Coding
Programming
Published
June 17, 2024
Author
Delger Bayanmunkh

Creating a Barcode Detector Using the Browser BarcodeDetector API

It seems there aren’t many open-source projects currently under maintenance about barcode detection. I have tried some old repositories and it resulted poor recognition. After doing some research I found there is a BarcodeDetector browser API that can detect any barcode and QR Code! How cool. Also, even if your target browser doesn’t support this api, there is a WebAssembly polyfill for god’s sake. Checkout for this purpose. Enough with the introduction. Let’s code!
In this tutorial, we'll create a simple barcode detector web application using the Browser BarcodeDetector API. The app will access the user's webcam, display the video stream, and detect barcodes in real-time. We'll also add a polyfill to support browsers that do not natively support the BarcodeDetector API.

Demo

Prerequisites

To follow along, you should have basic knowledge of HTML, CSS, and JavaScript.

Step 1: Setting Up the HTML

First, we'll set up our HTML structure. We'll need a video element to display the webcam stream and a paragraph element to display the detected barcode value. We'll also include scripts for the polyfill to ensure compatibility with unsupported browsers.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Barcode Detector</title> <script src="https://cdn.jsdelivr.net/npm/@undecaf/zbar-wasm@0.9.15/dist/index.js"></script> <script src="https://cdn.jsdelivr.net/npm/@undecaf/barcode-detector-polyfill@0.9.20/dist/index.js"></script> </head> <body> <h1>Barcode Detector</h1> <video id="video" width="640" height="480" autoplay></video> <p id="barcode-result">No barcode detected</p> <script> try { window['BarcodeDetector'].getSupportedFormats(); } catch { window['BarcodeDetector'] = barcodeDetectorPolyfill.BarcodeDetectorPolyfill; } </script> <script src="script.js"></script> </body> </html>

Step 2: Accessing the Webcam

Next, we'll request access to the user's webcam and stream the video to the video element. This involves using the navigator.mediaDevices.getUserMedia API.
// script.js const video = document.getElementById('video'); navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => { video.srcObject = stream; }) .catch(err => { console.error('Error accessing webcam: ', err); });

Step 3: Setting Up the Barcode Detector

Before we can use the BarcodeDetector API, we need to check if the browser supports it. We'll then create an instance of BarcodeDetector.
let barcodeDetector; if ('BarcodeDetector' in window) { barcodeDetector = new BarcodeDetector({ formats: ['code_128', 'ean_13', 'qr_code'] }); } else { console.error('Barcode Detector is not supported by this browser.'); }

Step 4: Detecting Barcodes

To detect barcodes, we need to process each frame from the video stream. We'll use the requestAnimationFrame method to create a loop that analyzes the video frames.
const barcodeResult = document.getElementById('barcode-result'); function detectBarcode() { if (barcodeDetector && video.readyState === HTMLVideoElement.HAVE_ENOUGH_DATA) { barcodeDetector.detect(video) .then(barcodes => { if (barcodes.length > 0) { barcodeResult.textContent = `Detected barcode: ${barcodes[0].rawValue}`; } }) .catch(err => { console.error('Barcode detection failed: ', err); }); } requestAnimationFrame(detectBarcode); } video.addEventListener('play', () => { requestAnimationFrame(detectBarcode); });

Complete Code

Here's the complete code for our barcode detector application:

HTML (index.html)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Barcode Detector</title> <script src="https://cdn.jsdelivr.net/npm/@undecaf/zbar-wasm@0.9.15/dist/index.js"></script> <script src="https://cdn.jsdelivr.net/npm/@undecaf/barcode-detector-polyfill@0.9.20/dist/index.js"></script> </head> <body> <h1>Barcode Detector</h1> <video id="video" width="640" height="480" autoplay></video> <p id="barcode-result">No barcode detected</p> <script> try { window['BarcodeDetector'].getSupportedFormats(); } catch { window['BarcodeDetector'] = barcodeDetectorPolyfill.BarcodeDetectorPolyfill; } </script> <script src="script.js"></script> </body> </html>

JavaScript (script.js)

const video = document.getElementById('video'); navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => { video.srcObject = stream; }) .catch(err => { console.error('Error accessing webcam: ', err); }); let barcodeDetector; if ('BarcodeDetector' in window) { barcodeDetector = new BarcodeDetector({ formats: ['code_128', 'ean_13', 'qr_code'] }); } else { console.error('Barcode Detector is not supported by this browser.'); } const barcodeResult = document.getElementById('barcode-result'); function detectBarcode() { if (barcodeDetector && video.readyState === HTMLVideoElement.HAVE_ENOUGH_DATA) { barcodeDetector.detect(video) .then(barcodes => { if (barcodes.length > 0) { barcodeResult.textContent = `Detected barcode: ${barcodes[0].rawValue}`; } }) .catch(err => { console.error('Barcode detection failed: ', err); }); } requestAnimationFrame(detectBarcode); } video.addEventListener('play', () => { requestAnimationFrame(detectBarcode); });

Conclusion

In this tutorial, we've created a simple web application that uses the BarcodeDetector API to detect barcodes from a live webcam feed. We've also included a polyfill to ensure compatibility with browsers that do not natively support the BarcodeDetector API. This is just a starting point, and you can extend this application by adding support for more barcode formats, improving the user interface, or integrating it with other services.
Happy coding!