Barcode Reader

This code sample shows how to read a barcode using the Image Capture API and Barcode Detection API. The code works only in a  secure environment (HTTPS).

Readings

ImageCapture – Web APIs | MDN (mozilla.org)
Barcode Detection API – Web APIs | MDN (mozilla.org)

Usage

Click the editbox below, the rear camera of the device is activated, frame the barcode and touch it.


if (!("BarcodeDetector" in window)) {
  log("Barcode Detector is not supported by this browser.", true);
} else
  log("Barcode Detector supported!");

let track, imageCapture, barcodeDetector;

function frameBarcode() {
  if (!imageCapture)
    navigator.mediaDevices
    .getUserMedia({
      "video": {
        facingMode: "environment"
      }
    })
    .then(mediaStream => {
      document.querySelector("#barcode").value = "";
      document.querySelector("#video").srcObject = mediaStream;

      track = mediaStream.getVideoTracks()[0];
      imageCapture = new ImageCapture(track);

      barcodeDetector = new BarcodeDetector({
        formats: ["code_39", "codabar", "ean_13"],
      });

      frameBarcode();
    })
    .catch(error => log(error, true));
  else {
    document.querySelector("#barcode").value = "";
    document.querySelector("#video").requestFullscreen();
    document.querySelector("#video").style.display = "";
    track.applyConstraints({
      advanced: [{
        torch: true
      }]
    });
  }
}

function readBarcode(event) {
  imageCapture
    .grabFrame()
    .then(imageBitmap => {
      barcodeDetector
        .detect(imageBitmap)
        .then(barcodes => {
          barcodes.forEach(barcode => {
            if (!document.querySelector("#barcode").value) {
              document.querySelector("#barcode").value = barcode.rawValue;
              document.querySelector("#barcode").scrollIntoView({
                block: "center"
              });
            }
          })
        })
    })
    .catch(error => log(error, true))
    .finally(() => {
      track.applyConstraints({
        advanced: [{
          torch: false
        }]
      });
      document.exitFullscreen();
      document.querySelector("#video").style.display = "none";
    });
}

 Last update 2023-05-31 04:51