Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

barcode-detector

Sec-ant303.5kMIT3.0.1TypeScript support: included

A Barcode Detection API polyfill that uses ZXing webassembly under the hood

es6, qrcode, barcode, barcode-detector, wasm, polyfill, zxing, esmodule, webassembly

readme

barcode-detector

npm npm bundle size (scoped) jsDelivr hits (npm scoped)

A Barcode Detection API ponyfill/polyfill that uses ZXing-C++ WebAssembly under the hood.

Supported barcode formats:

Linear Barcode Formats Matrix Barcode Formats Special Barcode Formats
codabar aztec    linear_codes[^2]
code_39 data_matrix    matrix_codes[^3]
code_93    maxi_code[^1]    any[^4]
code_128 pdf417
databar qr_code
databar_limited micro_qr_code
databar_expanded rm_qr_code
dx_film_edge |
ean_8 |
ean_13 |
itf |
upc_a |
upc_e

[^1]: Detection support for MaxiCode requires a pure monochrome image that contains an unrotated and unskewed symbol, along with a sufficient white border surrounding it.

[^2]: linear_codes is a shorthand for all linear barcode formats.

[^3]: matrix_codes is a shorthand for all matrix barcode formats.

[^4]: any is a shorthand for linear_codes and matrix_codes, i.e., all barcode formats. Note that you don't need to specify any in the formats option, as not providing the option also indicates detecting all barcode formats.

Install

To install, run the following command:

npm i barcode-detector

Usage

Ponyfill

import { BarcodeDetector } from "barcode-detector/ponyfill";

To avoid potential namespace collisions, you can also rename the export:

import { BarcodeDetector as BarcodeDetectorPonyfill } from "barcode-detector/ponyfill";

A ponyfill is a module required to be explicitly imported without introducing side effects. Use this subpath if you want to avoid polluting the global object with the BarcodeDetector class, or if you intend to use the implementation provided by this package instead of the native one.

Polyfill

import "barcode-detector/polyfill";

This subpath is used to polyfill the native BarcodeDetector class. It will automatically register the BarcodeDetector class in the global object if it's not already present.

[!IMPORTANT]

The polyfill will opt in only if no BarcodeDetector is present in globalThis. It basically works like this:

import { BarcodeDetector } from "barcode-detector/ponyfill";
globalThis.BarcodeDetector ??= BarcodeDetector;

Note that it doesn't check if the implementation is provided natively or by another polyfill. It also doesn't try to augment the existing implementation with all the barcode formats supported by this package. If you want all the features provided by this package, but you already have a native or another polyfilled BarcodeDetector, you should use the ponyfill approach. You can register it to the globalThis object manually if you want to.

Ponyfill + Polyfill

import { BarcodeDetector } from "barcode-detector";

This approach combines the ponyfill and polyfill approaches.

[!NOTE]

The ponyfill subpath was named pure and the polyfill subpath was named side-effects in early versions. They are no longer recommended for use and are considered deprecated. Please use the new subpaths as described above.

<script type="module">

For modern browsers that support ES modules, this package can be imported via the <script type="module"> tags:

  1. Include the polyfill:

    <!-- register -->
    <script
      type="module"
      src="https://fastly.jsdelivr.net/npm/barcode-detector@3/dist/es/polyfill.min.js"
    ></script>
    
    <!-- use -->
    <script type="module">
      const barcodeDetector = new BarcodeDetector();
    </script>
  2. Script scoped access:

    <script type="module">
      import { BarcodeDetector } from "https://fastly.jsdelivr.net/npm/barcode-detector@3/dist/es/ponyfill.min.js";
      const barcodeDetector = new BarcodeDetector();
    </script>
  3. With import maps:

    <!-- import map -->
    <script type="importmap">
      {
        "imports": {
          "barcode-detector/ponyfill": "https://fastly.jsdelivr.net/npm/barcode-detector@3/dist/es/ponyfill.min.js"
        }
      }
    </script>
    
    <!-- script scoped access -->
    <script type="module">
      import { BarcodeDetector } from "barcode-detector/ponyfill";
      const barcodeDetector = new BarcodeDetector();
    </script>

IIFE

For legacy browsers or userscripts that lack support for <script type="module"> tags, IIFE is the preferred choice. Upon executing the IIFE script, a variable named BarcodeDetectionAPI will be registered in the global window by var declaration.

<!-- 
  IIFE ponyfill.js registers:
  window.BarcodeDetectionAPI.BarcodeDetector
  window.BarcodeDetectionAPI.prepareZXingModule
  -->
<script src="https://fastly.jsdelivr.net/npm/barcode-detector@3/dist/iife/ponyfill.min.js"></script>

<!-- 
  IIFE polyfill.js registers:
  window.BarcodeDetector
  window.BarcodeDetectionAPI.prepareZXingModule
  -->
<script src="https://fastly.jsdelivr.net/npm/barcode-detector@3/dist/iife/polyfill.min.js"></script>

<!-- 
  IIFE index.js registers:
  window.BarcodeDetector
  window.BarcodeDetectionAPI.BarcodeDetector
  window.BarcodeDetectionAPI.prepareZXingModule
  -->
<script src="https://fastly.jsdelivr.net/npm/barcode-detector@3/dist/iife/index.min.js"></script>

prepareZXingModule

The core barcode reading functionality of this package is powered by zxing-wasm. Therefore, a .wasm binary file is fetched at runtime. By default, the .wasm serving path is initialized with a jsDelivr CDN URL. However, there're cases where this is not desired, such as the allowed serving path is white-listed by the Content Security Policy (CSP), or offline usage is required.

To customize the .wasm serving path, this package reexports prepareZXingModule along with ZXING_WASM_VERSION and ZXING_WASM_SHA256 from zxing-wasm. For more details on how to use them, please check Configuring .wasm Serving and Controlling .wasm Instantiation Timing and Caching sections in the zxing-wasm repository.

An example usage to override the .wasm serving path with an unpkg.com CDN url is as follows:

import {
  BarcodeDetector,
  ZXING_WASM_VERSION,
  prepareZXingModule,
} from "barcode-detector/ponyfill";

// Override the locateFile function
prepareZXingModule({
  overrides: {
    locateFile: (path, prefix) => {
      if (path.endsWith(".wasm")) {
        return `https://unpkg.com/zxing-wasm@${ZXING_WASM_VERSION}/dist/reader/${path}`;
      }
      return prefix + path;
    },
  },
});

// Now you can create a BarcodeDetector instance
const barcodeDetector = new BarcodeDetector({
  formats: ["qr_code"],
});

[!Note] The setZXingModuleOverrides method is deprecated in favor of prepareZXingModule.

API

Please check the spec, MDN doc and Chromium implementation for more information.

An example usage is as follows:

import { BarcodeDetector } from "barcode-detector/ponyfill";

// check supported formats
const supportedFormats = await BarcodeDetector.getSupportedFormats();

const barcodeDetector: BarcodeDetector = new BarcodeDetector({
  // make sure the formats are supported
  formats: ["qr_code"],
});

const imageFile = await fetch(
  "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=Hello%20world!",
).then((resp) => resp.blob());

barcodeDetector.detect(imageFile).then(console.log);

License

The source code in this repository is licensed under the MIT license.

changelog

barcode-detector

3.0.1

Patch Changes

  • 8206888: Bump zxing-wasm to v2.1.0 and other deps.

3.0.0

Generally, this release bumped the zxing-wasm dependency to v2 and renamed the subpath exports to ponyfill and polyfill from pure and side-effects. Detailed changes are as follows:

Breaking Changes

Renamed subpath exports

To avoid possible misunderstandings (we also use the term pure in zxing-wasm), the pure and side-effects subpath exports were renamed to ponyfill and polyfill, respectively. The old subpath exports are considered deprecated and are no longer recommended for use.

No longer a subclass of EventTarget

The BarcodeDetector class is no longer a subclass of EventTarget. BarcodeDetector wasn't designed to be an event target per the spec. This design was previously to allow for customized event handling. However, it causes more issues than it solves.

EAN-2/5 add-on symbols ignored

The EAN-2/5 add-on symbols were previously read if found. However, to align with the behavior of the native barcode detectors in Chromium and Safari on macOS, they are now ignored in this new version.

zxing-wasm v2

The zxing-wasm dependency was bumped to v2. This release includes breaking changes itself. For example, setZXingModuleOverrides is replaced by prepareZXingModule. Please refer to the README of zxing-wasm for detailed instructions on the new APIs.

Bug Fixes

Zero-sized Blob image no longer throws error

Per the spec, zero-sized ImageBitmapSource shouldn't cause errors to be thrown. Blob is one kind of the ImageBitmapSource and therefore should also comply with this rule. This is now fixed.

Fix TS moduleResolution: node subpath exports resolution

The subpath export types are now compatible with TypeScript's moduleResolution: node strategy by using the types-versions-wildcards strategy. This package now passes all the arethetypeswrong checks.

2.3.1

Patch Changes

  • 1698524: Bump zxing-wasm to v1.3.4 to fix PDF417 position info

2.3.0

Minor Changes

  • b9910bb: Add databar_limited detection support

2.2.12

Patch Changes

  • 139c454: Remove zxing-related tests as they are moved into the zxing-wasm repo.
  • 139c454: Pin @types/dom-webcodecs to 0.1.11 to avoid breaking types in projects using a lower version of TypeScript. Fixes #120.
  • 139c454: Bump zxing-wasm to 1.2.15. The success rate should be improved a lot.

2.2.11

Patch Changes

  • 1d27f3e: Fix image bitmap source type detection across iframes.

2.2.10

Patch Changes

  • 38e0b9f: Bump zxing-wasm to 1.2.14 to mitigate DOM Clobbering vulnerability.

2.2.9

Patch Changes

  • b0bfea1: Fix detecting HTML elements from iframes. See #110.

2.2.8

Patch Changes

  • 519cfe2: Preserve codabar start and end control chars. Fixes #91.
  • 70c58e1: Bump zxing-wasm and switch to pnpm and renovate

2.2.7

Patch Changes

  • 1da2c2b: Bump zxing-wasm to v1.2.11 and other dependencies

2.2.6

Patch Changes

  • 4af1507: Bump zxing-wasm to v1.2.10

2.2.5

Patch Changes

  • a7a46ee: Bump zxing-wasm to v1.2.7

2.2.4

Patch Changes

  • 48ab8ac: Bump zxing-wasm to v1.2.4.

2.2.3

Patch Changes

  • 529ec4e: bump zxing-wasm to v1.2.3