Back to Content

BarcodeDetector: detect() method

files/en-us/web/api/barcodedetector/detect/index.md

latest2.7 KB
Original Source

{{securecontext_header}}{{APIRef("Barcode Detector API")}}{{AvailableInWorkers}}{{SeeCompatTable}}

The detect() method of the {{domxref("BarcodeDetector")}} interface returns a {{jsxref('Promise')}} which fulfills with an {{jsxref('Array')}} of detected barcodes within an image.

Syntax

js-nolint
detect(imageBitmapSource)

Parameters

  • imageBitmapSource
    • : Receives an image source as a parameter. This can be a {{domxref("HTMLImageElement")}}, a {{domxref("SVGImageElement")}}, a {{domxref("HTMLVideoElement")}}, a {{domxref("HTMLCanvasElement")}}, an {{domxref("ImageBitmap")}}, an {{domxref("OffscreenCanvas")}}, a {{domxref("VideoFrame")}}, a {{domxref('Blob')}} of type image or an {{domxref('ImageData')}} object.

Return value

Returns a {{jsxref('Promise')}} which fulfills with an array of DetectedBarcode objects with the following properties:

  • boundingBox
    • : A {{domxref('DOMRectReadOnly')}}, which returns the dimensions of a rectangle representing the extent of a detected barcode, aligned with the image.
  • cornerPoints
    • : The x and y co-ordinates of the four corner points of the detected barcode relative to the image, starting with the top left and working clockwise. This may not be square due to perspective distortions within the image.
  • format
  • rawValue
    • : A string decoded from the barcode data.

Exceptions

  • {{jsxref("TypeError")}}
    • : Thrown if no parameter is specified or the type is not that of an ImageBitmapSource.
  • SecurityError {{domxref("DOMException")}}
    • : Thrown if the imageBitmapSource has an origin and is not the same as the document's origin, or if the imageBitmapSource is a {{domxref('HTMLCanvasElement')}} and its origin-clean flag is set to false.
  • InvalidStateError {{domxref("DOMException")}}
    • : Thrown if the imageBitmapSource is an {{domxref('HTMLImageElement')}} and is not fully decoded or decoding failed, or is an {{domxref('HTMLVideoElement')}} and its {{domxref('HTMLMediaElement.readyState', 'readyState')}} is HAVE_NOTHING or HAVE_METADATA.

Examples

This example uses the detect() method to detect the barcodes within the given image. These are iterated over and the barcode data is logged to the console.

js
barcodeDetector
  .detect(imageEl)
  .then((barcodes) => {
    barcodes.forEach((barcode) => console.log(barcode.rawValue));
  })
  .catch((err) => {
    console.error(err);
  });

Specifications

{{Specifications}}

Browser compatibility

{{Compat}}