Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
ZXing JS Browser
https://github.com/zxing-js/browser
Admin
ZXing for JS's browser layer with decoding implementations for browser.
Tokens:
64,071
Snippets:
385
Trust Score:
8.2
License:
MIT
Update:
1 week ago
Context
Chat
Benchmark
91.59
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install @zxing/browser with yarn or npm Source: https://github.com/zxing-js/browser/blob/master/README.md Install the @zxing/browser package using either yarn or npm. ```bash yarn add @zxing/browser ``` ```bash npm i @zxing/browser ``` -------------------------------- ### Using decodeFromVideoDevice with device selection Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Example usage of `decodeFromVideoDevice`. It lists available video input devices, selects the first one, and starts decoding with a callback that logs the result text. The scanner is stopped after 20 seconds using `controls.stop()`. ```ts const devices = await BrowserCodeReader.listVideoInputDevices(); const controls = await codeReader.decodeFromVideoDevice( devices[0].deviceId, previewVideo, (result, error) => { if (result) console.log(result.getText()); }, ); setTimeout(() => controls.stop(), 20000); // stop after 20s ``` -------------------------------- ### decodeFromVideoUrl usage example Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Usage example for decodeFromVideoUrl. Pass a video URL and a callback that receives each decode attempt result. The returned controls can be used to stop scanning. ```ts const controls = await codeReader.decodeFromVideoUrl('https://example.com/barcode-video.mp4', (result) => { if (result) console.log(result.getText()); }); ``` -------------------------------- ### Usage example for BrowserCodeSvgWriter subclass Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeSvgWriter.md Shows how to extend BrowserCodeSvgWriter and instantiate it with a container id. ```typescript import { BrowserCodeSvgWriter } from '@zxing/browser'; class MyWriter extends BrowserCodeSvgWriter { constructor(container: string | HTMLElement) { super(container); } } const writer = new MyWriter('#svg-container'); ``` -------------------------------- ### decodeOnceFromVideoUrl usage example Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Example usage of decodeOnceFromVideoUrl with a video URL. Logs the decoded text or an error if no barcode is found or the video is unplayable. ```ts try { const result = await codeReader.decodeOnceFromVideoUrl('https://example.com/video.mp4'); console.log(result.getText()); } catch (e) { console.error('No barcode found or video unplayable:', e); } ``` -------------------------------- ### Using ZXingBrowser UMD global namespace Source: https://github.com/zxing-js/browser/blob/master/_autodocs/configuration.md Use the global ZXingBrowser namespace when loading the UMD build via a script tag. This example creates a BrowserQRCodeReader instance and lists available video input devices. ```javascript const codeReader = new ZXingBrowser.BrowserQRCodeReader(); const devices = await ZXingBrowser.BrowserCodeReader.listVideoInputDevices(); ``` -------------------------------- ### Customize reader timing options with BrowserQRCodeReader Source: https://github.com/zxing-js/browser/blob/master/_autodocs/configuration.md Example of constructing a BrowserQRCodeReader with custom timing options. Options are resolved once at construction time; the possibleFormats setter and BrowserMultiFormatReader.setHints do not affect these timings. ```typescript import { BrowserQRCodeReader } from '@zxing/browser'; const codeReader = new BrowserQRCodeReader(undefined, { delayBetweenScanSuccess: 200, // faster re-scans after a hit delayBetweenScanAttempts: 1000, // slower retries after errors tryPlayVideoTimeout: 3000, // shorter video wait }); ``` -------------------------------- ### scanOneResult usage example Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Creates a BrowserQRCodeReader and awaits the first successful decode from a video element. The scan loop stops on success and rejects with the first non-retried error when the matching retryIf* flag is false. ```typescript const codeReader = new BrowserQRCodeReader(); const result = await codeReader.scanOneResult(videoElement); ``` -------------------------------- ### decodeFromConstraints Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Starts continuous decoding from a media stream obtained via getUserMedia with the given constraints. Returns scanner controls for managing the scanning session. ```APIDOC ## `decodeFromConstraints` ```ts public async decodeFromConstraints( constraints: MediaStreamConstraints, previewElem: string | HTMLVideoElement | undefined, callbackFn: DecodeContinuouslyCallback, ): Promise<IScannerControls> { ``` Source: `src/readers/BrowserCodeReader.ts:643` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | constraints | `MediaStreamConstraints` | yes | — | WebRTC media constraints used to obtain a `MediaStream` via `navigator.mediaDevices.getUserMedia`. | | previewElem | `string \| HTMLVideoElement \| undefined` | yes | — | Video element (or its id) in which the stream is shown while decoding; `undefined` shows no video. | | callbackFn | `DecodeContinuouslyCallback` | yes | — | Per-attempt callback (see `scan`). | **Returns:** `Promise<IScannerControls>` — resolves once the stream is attached and scanning has started. Rejects if the user denies camera permission or no matching device exists (the stream is disposed on error). The stream is fetched with `getUserMedia(constraints)` and tracked by the class for cleanup by `releaseAllStreams()`. ```ts const controls = await codeReader.decodeFromConstraints( { video: { facingMode: 'environment' } }, previewVideo, (result, error, controls) => { if (result) console.log(result.getText()); }, ); ``` ``` -------------------------------- ### Continuous webcam scan with BrowserAztecCodeReader Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserAztecCodeReader.md Configures a BrowserAztecCodeReader with a delay of 300ms between successful scans and starts continuous decoding from a video device, stopping on the first successful result. ```typescript import { BrowserAztecCodeReader } from '@zxing/browser'; const codeReader = new BrowserAztecCodeReader(undefined, { delayBetweenScanSuccess: 300, // faster consecutive attempts }); // Continuous webcam scan, stop on first Aztec code const controls = await codeReader.decodeFromVideoDevice(undefined, previewVideo, (res) => { if (res) { console.log(res.getText()); controls.stop(); } }); ``` -------------------------------- ### write with hints and error handling Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserQRCodeSvgWriter.md Shows how to pass encode hints (ERROR_CORRECTION and MARGIN) to the write method and how to handle IllegalArgumentException when encoding empty content. The example appends the resulting SVG to document.body. ```typescript import { BrowserQRCodeSvgWriter } from '@zxing/browser'; import { EncodeHintType, IllegalArgumentException } from '@zxing/library'; const writer = new BrowserQRCodeSvgWriter(); // With hints const hints = new Map<EncodeHintType, any>(); hints.set(EncodeHintType.ERROR_CORRECTION, 'H'); hints.set(EncodeHintType.MARGIN, 2); const svg = writer.write('payload', 250, 250, hints); document.body.appendChild(svg); // Error handling try { writer.write('', 100, 100); } catch (e) { if (e instanceof IllegalArgumentException) { console.error('Empty content cannot be encoded'); } } ``` -------------------------------- ### decodeFromVideoDevice Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Starts continuous decoding from a video device (camera). The deviceId is translated into constraints: `{ video: { deviceId: { exact: deviceId } } }`, or `{ video: { facingMode: 'environment' } }` when deviceId is falsy. Delegates to decodeFromConstraints. ```APIDOC ## `decodeFromVideoDevice` ### Description Starts continuous decoding from a video device (camera). The `deviceId` is translated into constraints: `{ video: { deviceId: { exact: deviceId } } }`, or `{ video: { facingMode: 'environment' } }` when `deviceId` is falsy. Delegates to `decodeFromConstraints`. ### Method `decodeFromVideoDevice` ### Signature ```ts public async decodeFromVideoDevice( deviceId: string | undefined, previewElem: string | HTMLVideoElement | undefined, callbackFn: DecodeContinuouslyCallback, ): Promise<IScannerControls> ``` ### Parameters - `deviceId` (`string | undefined`) - Required - Id of a device from `listVideoInputDevices()`. `undefined` selects the environment-facing camera if available. - `previewElem` (`string | HTMLVideoElement | undefined`) - Required - Preview video element (or id); `undefined` to show no preview. - `callbackFn` (`DecodeContinuouslyCallback`) - Required - Per-attempt callback. ### Returns `Promise<IScannerControls>` — see `decodeFromConstraints`. ### Example ```ts const devices = await BrowserCodeReader.listVideoInputDevices(); const controls = await codeReader.decodeFromVideoDevice( devices[0].deviceId, previewVideo, (result, error) => { if (result) console.log(result.getText()); }, ); setTimeout(() => controls.stop(), 20000); // stop after 20s ``` ``` -------------------------------- ### Using HTMLCanvasElementLuminanceSource with BrowserCodeReader Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/HTMLCanvasElementLuminanceSource.md Example usage of HTMLCanvasElementLuminanceSource. Creates a canvas element, draws something on it, then creates a luminance source from the canvas and generates a binary bitmap using BrowserCodeReader. ```ts import { HTMLCanvasElementLuminanceSource, BrowserCodeReader } from '@zxing/browser'; const canvas = document.createElement('canvas'); // ...draw something on canvas... const source = new HTMLCanvasElementLuminanceSource(canvas); const bitmap = BrowserCodeReader.createBinaryBitmapFromCanvas(canvas); ``` -------------------------------- ### Import BrowserQRCodeReader with ES6 modules Source: https://github.com/zxing-js/browser/blob/master/README.md Import BrowserQRCodeReader using ES6 modules and create an instance. ```html <script type="module"> import { BrowserQRCodeReader } from '@zxing/browser'; const codeReader = new BrowserQRCodeReader(); // do something with codeReader... </script> ``` -------------------------------- ### Asynchronously import BrowserQRCodeReader Source: https://github.com/zxing-js/browser/blob/master/README.md Asynchronously import BrowserQRCodeReader using dynamic import. ```html <script type="module"> import('@zxing/browser').then(({ BrowserQRCodeReader }) => { const codeReader = new BrowserQRCodeReader(); // do something with codeReader... }); </script> ``` -------------------------------- ### Importing @zxing/browser Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/index.md Shows three ways to import the @zxing/browser package: ES6 module import, asynchronous import, and UMD global namespace. Each creates a BrowserQRCodeReader instance. ```javascript // ES6 module import { BrowserQRCodeReader } from '@zxing/browser'; const codeReader = new BrowserQRCodeReader(); ``` ```javascript // Asynchronous import import('@zxing/browser').then(({ BrowserQRCodeReader }) => { const codeReader = new BrowserQRCodeReader(); }); ``` ```javascript // UMD — the global namespace is ZXingBrowser const codeReader = new ZXingBrowser.BrowserQRCodeReader(); ``` -------------------------------- ### decodeFromVideoElement Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Starts continuous decoding from a `<video>` element. Applies the `autoplay`, `muted` and `playsinline` attributes (needed for iOS 11), waits for the video to become playable (bounded by `options.tryPlayVideoTimeout`, default 5000 ms), plays it, then starts `scan`. The caller-owned element is not cleaned up by `stop()`. ```APIDOC ## `decodeFromVideoElement` ### Description Starts continuous decoding from a `<video>` element. Applies the `autoplay`, `muted` and `playsinline` attributes (needed for iOS 11), waits for the video to become playable (bounded by `options.tryPlayVideoTimeout`, default 5000 ms), plays it, then starts `scan`. The caller-owned element is not cleaned up by `stop()`. ### Method `decodeFromVideoElement` ### Signature ```ts public async decodeFromVideoElement( source: string | HTMLVideoElement, callbackFn: DecodeContinuouslyCallback, ): Promise<IScannerControls> ``` ### Parameters - `source` (`string | HTMLVideoElement`) - Required - Id of a `<video>` element or the element itself. - `callbackFn` (`DecodeContinuouslyCallback`) - Required - Per-attempt callback. ### Returns `Promise<IScannerControls>`. ### Throws / Rejects - `ArgumentException` if `source` is falsy. - Rejects if the video never becomes playable within the timeout. ### Example ```ts const controls = await codeReader.decodeFromVideoElement('my-video-id', (result) => { if (result) console.log(result.getText()); }); ``` ``` -------------------------------- ### Importing @zxing/browser Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/index.md Shows how to import the @zxing/browser package using ES6 modules, asynchronous import, or UMD global namespace. ```APIDOC ## Importing ### ES6 module ```js import { BrowserQRCodeReader } from '@zxing/browser'; const codeReader = new BrowserQRCodeReader(); ``` ### Asynchronous import ```js import('@zxing/browser').then(({ BrowserQRCodeReader }) => { const codeReader = new BrowserQRCodeReader(); }); ``` ### UMD (global namespace ZXingBrowser) ```js const codeReader = new ZXingBrowser.BrowserQRCodeReader(); ``` ``` -------------------------------- ### Load ZXingBrowser with UMD Source: https://github.com/zxing-js/browser/blob/master/README.md Load ZXingBrowser using UMD and instantiate after window load. ```html <script type="text/javascript" src="https://unpkg.com/@zxing/browser@latest"></script> <script type="text/javascript"> window.addEventListener('load', () => { const codeReader = new ZXingBrowser.BrowserQRCodeReader(); // do something with codeReader... }); </script> ``` -------------------------------- ### Basic usage of decodeFromImageUrl Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader.md Example usage of decodeFromImageUrl with a BrowserQRCodeReader instance. The result's getText() method outputs the decoded barcode text. ```ts const codeReader = new BrowserQRCodeReader(); const source = 'https://my-image-or-video/01.png'; const result = await codeReader.decodeFromImageUrl(source); console.log(result.getText()); ``` -------------------------------- ### Load ZXingBrowser with AMD Source: https://github.com/zxing-js/browser/blob/master/README.md Load ZXingBrowser using AMD with requirejs. ```html <script type="text/javascript" src="https://unpkg.com/requirejs"></script> <script type="text/javascript"> require(['@zxing/browser'], ZXingBrowser => { const codeReader = new ZXingBrowser.BrowserQRCodeReader(); // do something with codeReader... }); </script> ``` -------------------------------- ### decodeFromImageUrl with error handling Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader.md Example showing error handling when calling decodeFromImageUrl. Note that URL images must be CORS-accessible for canvas pixel reads. ```ts // URL images must be CORS-accessible for canvas pixel reads const codeReader = new BrowserQRCodeReader(); try { const result = await codeReader.decodeFromImageUrl('https://example.com/qr.png'); } catch (e) { console.error('Failed to load or decode the image:', e); } ``` -------------------------------- ### Basic usage with subclass Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeSvgWriter.md Shows how to subclass BrowserCodeSvgWriter and write a QR code to an SVG element. The example logs the width attribute of the resulting SVG. ```typescript import { BrowserCodeSvgWriter, HTMLVisualMediaElement } from '@zxing/browser'; // Subclass and use class QrWriter extends BrowserCodeSvgWriter {} const writer = new QrWriter(document.getElementById('output')); const svg = writer.write('https://example.com', 200, 200); console.log('Done', svg.getAttribute('width')); ``` -------------------------------- ### Basic writeToDom usage Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserQRCodeSvgWriter.md Basic usage of writeToDom with a CSS selector. Creates a BrowserQRCodeSvgWriter instance and writes a QR code for 'https://example.com' into the element matching '#qr-placeholder' with 200x200 pixels. ```typescript import { BrowserQRCodeSvgWriter } from '@zxing/browser'; const writer = new BrowserQRCodeSvgWriter(); writer.writeToDom('#qr-placeholder', 'https://example.com', 200, 200); ``` -------------------------------- ### Using decodeFromVideoElement with video element id Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Example usage of `decodeFromVideoElement` with a video element id. The callback logs the result text when a barcode is decoded. ```ts const controls = await codeReader.decodeFromVideoElement('my-video-id', (result) => { if (result) console.log(result.getText()); }); ``` -------------------------------- ### decodeFromStream Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Starts continuous barcode decoding from an existing MediaStream. Returns a Promise of IScannerControls with extended stream introspection methods and optional torch control. ```APIDOC ## decodeFromStream ### Description Starts continuous barcode decoding from an already-obtained webcam MediaStream. Returns a Promise of IScannerControls extended with stream introspection methods and optional torch control. ### Method `decodeFromStream` (async method) ### Signature ```ts public async decodeFromStream( stream: MediaStream, preview: string | HTMLVideoElement | undefined, callbackFn: DecodeContinuouslyCallback, ): Promise<IScannerControls> ``` ### Parameters - **stream** (`MediaStream`) - Required - An already-obtained webcam MediaStream (e.g. from `navigator.mediaDevices.getUserMedia`). Neither this method nor its `stop()` disposes the stream unless a torch-compatible track is found. - **preview** (`string | HTMLVideoElement | undefined`) - Required - Video element (or its id) where the stream is previewed; `undefined` plays without preview. - **callbackFn** (`DecodeContinuouslyCallback`) - Required - Per-attempt callback. ### Returns `Promise<IScannerControls>` — the standard controls extended with stream introspection: | Extra control | Signature | |---------------|-----------| | `streamVideoConstraintsApply` | `(constraints: MediaTrackConstraints, trackFilter?: (track: MediaStreamTrack) => MediaStreamTrack[]) => void` | | `streamVideoConstraintsGet` | `(trackFilter: (track: MediaStreamTrack) => MediaStreamTrack[]) => MediaTrackConstraints` | | `streamVideoSettingsGet` | `(trackFilter: (track: MediaStreamTrack) => MediaStreamTrack[]) => MediaTrackSettings` | | `streamVideoCapabilitiesGet` | `(trackFilter: (track: MediaStreamTrack) => MediaStreamTrack[]) => MediaTrackCapabilities` | | `switchTorch` | `(onOff: boolean) => Promise<void>` — only present if the stream has a torch-compatible track | When the stream is torch-compatible, `stop()` is overridden to first turn the torch off (`applyConstraints({ advanced: [{ fillLightMode: onOff ? 'flash' : 'off', torch: onOff }] })` on the compatible track) and the `streamTracker` reference is released. Torch support is experimental and browser-dependent. ### Example ```ts // Obtain a stream yourself, then scan it const stream = await navigator.mediaDevices.getUserMedia({ video: {} }); const controls = await codeReader.decodeFromStream(stream, previewVideo, (result) => { if (result) console.log(result.getText()); }); // Read the applied constraints of the first video track if (controls.streamVideoConstraintsGet) { const c = controls.streamVideoConstraintsGet((track) => track.getKind() === 'video' ? [track] : []); console.log(c); } ``` ```ts // Optionally toggle the torch when available if (controls.switchTorch) { await controls.switchTorch(true); // ... scanning under fill light ... await controls.switchTorch(false); } ``` ``` -------------------------------- ### new BrowserAztecCodeReader(hints?, options?) Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserAztecCodeReader.md Creates a new BrowserAztecCodeReader instance. The constructor initializes the underlying AztecCodeReader and forwards optional decode hints and timing options to the base class. ```APIDOC ## Constructor ### Description Creates a new BrowserAztecCodeReader instance, wrapping AztecCodeReader from @zxing/library. ### Method Constructor ### Signature ```ts public constructor( hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions, ) ``` ### Parameters - **hints** (`Map<DecodeHintType, any>`) - Optional - Decode hints forwarded to the base class and reader. Defaults to `new Map<DecodeHintType, any>()`. - **options** (`IBrowserCodeReaderOptions`) - Optional - Timing options; see configuration.md for details. Defaults to `{}`. ### Description Creates a new BrowserAztecCodeReader instance. The underlying AztecCodeReader is created internally; no arguments are required. ``` ```APIDOC ## Constructor ### Description Creates a new BrowserAztecCodeReader instance that wraps an AztecCodeReader for decoding Aztec codes in the browser. ### Method Constructor ### Endpoint `new BrowserAztecCodeReader(hints?, options?)` ### Parameters #### Constructor Parameters - **hints** (`Map<DecodeHintType, any>`) - Optional - Decode hints forwarded to the base class and reader. Defaults to `new Map<DecodeHintType, any>()`. - **options** (`IBrowserCodeReaderOptions`) - Optional - Timing options; see configuration.md. ### Request Example ```ts const codeReader = new BrowserAztecCodeReader(); ``` ### Response #### Success Response - **codeReader** (BrowserAztecCodeReader) - A new instance of the reader. #### Response Example ```ts const codeReader = new BrowserAztecCodeReader(); ``` ``` ```APIDOC ## Constructor ### Description Creates a new BrowserAztecCodeReader instance that wraps an internal AztecCodeReader for decoding Aztec codes from browser media elements. ### Method Constructor ### Endpoint `new BrowserAztecCodeReader(hints?, options?)` ### Parameters #### Constructor Parameters - **hints** (`Map<DecodeHintType, any>`) - Optional - Decode hints forwarded to the base class and reader. - **options** (`IBrowserCodeReaderOptions`) - Optional - Timing options; see configuration.md. ### Request Example ```ts const codeReader = new BrowserAztecCodeReader(); ``` ### Response No return value (constructor). ``` ```APIDOC ## Constructor ### Description Creates a new BrowserAztecCodeReader instance that wraps an internal AztecCodeReader. ### Method constructor ### Parameters - **hints** (`Map<DecodeHintType, any>`) - Optional - Decode hints forwarded to the base class and reader. - **options** (`IBrowserCodeReaderOptions`) - Optional - Timing options; see configuration.md. ### Request Example ```ts const codeReader = new BrowserAztecCodeReader(); ``` ``` -------------------------------- ### new BrowserPDF417Reader(hints?, options?) Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserPDF417Reader.md Creates a new BrowserPDF417Reader instance. The constructor accepts optional decode hints and timing options, and internally creates a PDF417Reader instance. ```APIDOC ## [CONSTRUCTOR] new BrowserPDF417Reader(hints?, options?) ### Description Creates a new BrowserPDF417Reader instance for decoding PDF417 barcodes in the browser. The constructor initializes the underlying PDF417Reader and forwards optional hints and timing options to the base class. ### Method constructor ### Endpoint new BrowserPDF417Reader(hints?, options?) ### Parameters #### Constructor Parameters - **hints** (Map<DecodeHintType, any>) - Optional - Decode hints forwarded to the base class and reader. Defaults to `new Map<DecodeHintType, any>()`. - **options** (IBrowserCodeReaderOptions) - Optional - Timing options; see configuration.md. ### Request Example ```ts const codeReader = new BrowserPDF417Reader(); ``` ### Response #### Success Response - **codeReader** (BrowserPDF417Reader) - A new instance of the reader. #### Response Example ```ts const codeReader = new BrowserPDF417Reader(); ``` ``` -------------------------------- ### scan method signature — continuous decode loop Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Starts a continuous decode loop on an <img> or <video> element. The element is not disposed or destroyed by this method. ```TypeScript public scan( element: HTMLVisualMediaElement, callbackFn: DecodeContinuouslyCallback, finalizeCallback?: (error?: Error) => void, ): IScannerControls { ``` -------------------------------- ### BrowserQRCodeReader constructor Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserQRCodeReader.md Constructor for the BrowserQRCodeReader class. It accepts optional decode hints and options, and creates a new instance with a QRCodeReader decoder. ```APIDOC ## Constructor ### Description Creates a new `BrowserQRCodeReader` instance. It is a thin subclass of `BrowserCodeReader` that injects a `QRCodeReader` (from `@zxing/library`) as the decoder. ### Method constructor ### Parameters - **hints** (`Map<DecodeHintType, any>`) - Optional - Decode hints forwarded to the base class and reader. Default: `new Map<DecodeHintType, any>()`. - **options** (`IBrowserCodeReaderOptions`) - Optional - Timing options; see configuration.md. Default: `{}`. ### Request Example ```ts const codeReader = new BrowserQRCodeReader(); ``` ```ts import { BrowserQRCodeReader } from '@zxing/browser'; import { DecodeHintType } from '@zxing/library'; // Pass decode hints and tuned timing at construction const hints = new Map<DecodeHintType, any>(); hints.set(DecodeHintType.TRY_HARDER, true); const codeReader = new BrowserQRCodeReader(hints, { delayBetweenScanSuccess: 250, delayBetweenScanAttempts: 1000, tryPlayVideoTimeout: 3000, }); ``` ### Response No return value. The instance is ready to use for decoding. ``` -------------------------------- ### Load @zxing/browser via UNPKG script tag Source: https://github.com/zxing-js/browser/blob/master/README.md Load the ZXingBrowser library via a script tag from UNPKG CDN. ```html <!-- loading ZXingBrowser via UNPKG --> <script type="text/javascript" src="https://unpkg.com/@zxing/browser@latest"></script> ``` -------------------------------- ### prepareImageElement: Obtain an image element from element, id, or new Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Creates or resolves an HTMLImageElement. Accepts an existing element, a DOM id (resolved via getMediaElement), or undefined (creates a new 200x200 img element). Throws a plain Error for any other input. ```ts public static prepareImageElement(imageSource?: HTMLImageElement | string): HTMLImageElement { if (imageSource instanceof HTMLImageElement) { return imageSource; } if (typeof imageSource === 'string') { return BrowserCodeReader.getMediaElement(imageSource, 'img') as HTMLImageElement; } if (typeof imageSource === 'undefined') { const imageElement = document.createElement('img'); imageElement.width = 200; imageElement.height = 200; return imageElement; } throw new Error('Couldn\'t get imageElement from imageSource!'); } ``` -------------------------------- ### Setting possibleFormats on BrowserMultiFormatReader Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader.md Example usage that creates a BrowserMultiFormatReader and assigns an array of barcode formats to the possibleFormats setter. Note that BrowserMultiFormatReader overrides this setter to also push the hints into its MultiFormatReader. ```typescript import { BrowserMultiFormatReader, BarcodeFormat } from '@zxing/browser'; const reader = new BrowserMultiFormatReader(); reader.possibleFormats = [BarcodeFormat.QR_CODE, BarcodeFormat.AZTEC]; ``` -------------------------------- ### listVideoInputDevices Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Asynchronously enumerates all available video input devices and returns an array of MediaDeviceInfo objects. Throws an error if the navigator is not present or if device enumeration is not supported. ```APIDOC ## `listVideoInputDevices` ### Description Asynchronously enumerates all available video input devices and returns an array of `MediaDeviceInfo` objects. Throws an error if the navigator is not present or if device enumeration is not supported. ### Method `BrowserCodeReader.listVideoInputDevices()` ### Parameters None ### Returns `Promise<MediaDeviceInfo[]>` — an array of `MediaDeviceInfo` objects for video input devices, each with `deviceId`, `label`, `kind`, and `groupId`. ### Throws - `Error` if `navigator` is not present. - `Error` if `navigator.mediaDevices.enumerateDevices` is not supported. ### Example ts const devices = await BrowserCodeReader.listVideoInputDevices(); console.log(devices[0].deviceId, devices[0].label); ``` -------------------------------- ### createVideoElement: Obtain a video element from element, id, or new Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Creates or resolves an HTMLVideoElement. Accepts an existing element, a DOM id (resolved via getMediaElement), or nothing (creates a new 200x200 video element). Throws ArgumentException for a non-matching id and a plain Error when nothing usable is passed and document is undefined. ```ts public static createVideoElement(videoThingy?: HTMLVideoElement | string): HTMLVideoElement { if (videoThingy instanceof HTMLVideoElement) { return videoThingy; } if (typeof videoThingy === 'string') { return BrowserCodeReader.getMediaElement(videoThingy, 'video') as HTMLVideoElement; } if (!videoThingy && typeof document !== 'undefined') { const videoElement = document.createElement('video'); videoElement.width = 200; videoElement.height = 200; return videoElement; } throw new Error('Couldn\'t get videoElement from videoSource!'); } ``` -------------------------------- ### scan — continuous decode loop Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Starts a continuous decode loop on a video or image element, invoking the callback after every scan attempt. Returns an IScannerControls object to stop the loop. ```APIDOC ## scan(element, callbackFn, finalizeCallback?) — continuous decode loop ### Description Starts a continuous decode loop on the provided HTML visual media element (e.g., `<video>` or `<img>`). The callback is invoked after every scan attempt with the result or error, and an `IScannerControls` object is returned to stop the loop. ### Method `scan` ### Signature ```ts public scan( element: HTMLVisualMediaElement, callbackFn: DecodeContinuouslyCallback, finalizeCallback?: (error?: Error) => void, ): IScannerControls ``` ### Parameters - **element** (`HTMLVisualMediaElement`) - Required - The `<img>` / `<video>` element to scan. It is **not** disposed or destroyed by this method. - **callbackFn** (`DecodeContinuouslyCallback`) - Required - Called after every scan attempt: `(result, error, controls)`. - **finalizeCallback** (`(error?: Error) => void`) - Optional - Called exactly once when the scan ends (via `stop()` or on an unrecoverable error). Receives the error for error-ended scans, `undefined` for `stop()`. ### Returns `IScannerControls` — a control object with a `stop()` method that halts the loop, clears the pending timeout, disposes the capture canvas, and invokes `finalizeCallback`. ### Throws - `ArgumentException` if `callbackFn` is missing. - `Error` if the capture canvas cannot be created. ### Loop Behavior 1. A capture canvas is created and its 2D context obtained (with `{ willReadFrequently: true }`). 2. Each iteration draws the current media frame on the canvas (`drawImageOnCanvas`), decodes it (`decodeFromCanvas`), then calls `callbackFn(result, undefined, controls)`. 3. On success the loop waits `this.options.delayBetweenScanSuccess` ms before the next iteration. 4. On failure the loop calls `callbackFn(undefined, error, controls)`. For `ChecksumException`, `FormatException` or `NotFoundException` it retries after `this.options.delayBetweenScanAttempts` ms; **any other error** disposes the canvas, calls `finalizeCallback(error)`, and stops. ### Example ```ts const codeReader = new BrowserQRCodeReader(); const video = document.querySelector('#scan-preview'); const controls = codeReader.scan(video, (result, error, controls) => { if (result) { console.log('Found:', result.getText()); controls.stop(); // stop after first hit } else if (error) { console.warn('Attempt failed:', error); } }); // elsewhere controls.stop(); ``` ### Example with finalize callback ```ts // With finalize callback (always logs when the loop ends) const controls = codeReader.scan( video, (result, error) => { /* per-attempt */ }, (finalError) => { if (finalError) console.error('Scan aborted:', finalError); else console.log('Scan stopped cleanly.'); }, ); ``` ``` -------------------------------- ### listVideoInputDevices: Enumerate video input devices Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Static async method that returns a Promise resolving to an array of MediaDeviceInfo objects for videoinput devices. Throws a plain Error when navigator is absent or when device enumeration is unsupported. Maps each device to { deviceId, label, kind, groupId }, falling back to a generated label like 'Video device N'. ```typescript public static async listVideoInputDevices(): Promise<MediaDeviceInfo[]> { if (!hasNavigator()) { throw new Error('Can\'t enumerate devices, navigator is not present.'); } if (!canEnumerateDevices()) { throw new Error('Can\'t enumerate devices, method not supported.'); } const devices = await navigator.mediaDevices.enumerateDevices(); const videoDevices: MediaDeviceInfo[] = []; for (const device of devices) { const kind = device.kind as string === 'video' ? 'videoinput' : device.kind; if (kind !== 'videoinput') { continue; } const deviceId = device.deviceId || (device as any).id; const label = device.label || `Video device ${videoDevices.length + 1}`; const groupId = device.groupId; const videoDevice = { deviceId, label, kind, groupId } as MediaDeviceInfo; videoDevices.push(videoDevice); } return videoDevices; } ``` ``` -------------------------------- ### HTMLCanvasElementLuminanceSource constructor Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/HTMLCanvasElementLuminanceSource.md Constructor for HTMLCanvasElementLuminanceSource. Reads the canvas pixels immediately and converts RGBA data to a grayscale buffer. Throws an Error ('Couldn't get canvas context.') if the canvas has no usable 2D context. ```ts public constructor(private canvas: HTMLCanvasElement) { super(canvas.width, canvas.height); this.buffer = HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(canvas); } ``` -------------------------------- ### Import BrowserQRCodeReader from @zxing/browser Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserQRCodeReader.md Imports the BrowserQRCodeReader class from the @zxing/browser package. Use this to access the QR Code–specific browser reader. ```typescript import { BrowserQRCodeReader } from '@zxing/browser'; ``` -------------------------------- ### Import BrowserQRCodeSvgWriter from @zxing/browser Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserQRCodeSvgWriter.md Import the BrowserQRCodeSvgWriter class from the @zxing/browser package. Use this when you need to create QR code SVG output in a browser environment. ```typescript import { BrowserQRCodeSvgWriter } from '@zxing/browser'; ``` -------------------------------- ### getMediaElementDimensions: Get intrinsic dimensions of media element Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Returns the intrinsic dimensions of a video or image element. For videos uses videoHeight/videoWidth; for images uses naturalHeight/naturalWidth falling back to the height/width attributes. Throws a plain Error for any other element type. ```ts public static getMediaElementDimensions(mediaElement: HTMLVisualMediaElement) { if (mediaElement instanceof HTMLVideoElement) { return { height: mediaElement.videoHeight, width: mediaElement.videoWidth, }; } if (mediaElement instanceof HTMLImageElement) { return { height: mediaElement.naturalHeight || mediaElement.height, width: mediaElement.naturalWidth || mediaElement.width, }; } throw new Error('Couldn\'t find the Source\'s dimensions!'); } ``` -------------------------------- ### decodeFromVideoElement method signature Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-video.md Method signature for continuously decoding from a video element. Applies `autoplay`, `muted`, and `playsinline` attributes (needed for iOS 11), waits for the video to become playable (bounded by `options.tryPlayVideoTimeout`, default 5000 ms), plays it, then starts `scan`. The caller-owned element is not cleaned up by `stop()`. Throws `ArgumentException` if `source` is falsy; rejects if the video never becomes playable within the timeout. ```ts public async decodeFromVideoElement( source: string | HTMLVideoElement, callbackFn: DecodeContinuouslyCallback, ): Promise<IScannerControls> { ``` -------------------------------- ### prepareVideoElement: Configure video element for iOS 11 autoplay Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Resolves a video element via createVideoElement and sets the autoplay, muted, and playsinline attributes as an autoplay workaround for iOS 11. Returns the configured element. ```ts public static prepareVideoElement(videoElem?: HTMLVideoElement | string): HTMLVideoElement { const videoElement = BrowserCodeReader.createVideoElement(videoElem); // Needed for iOS 11 videoElement.setAttribute('autoplay', 'true'); videoElement.setAttribute('muted', 'true'); videoElement.setAttribute('playsinline', 'true'); return videoElement; } ``` -------------------------------- ### BrowserQRCodeReader constructor Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserQRCodeReader.md Constructs a BrowserQRCodeReader with optional decode hints and timing options. Both parameters are optional and default to an empty map and empty object respectively. ```typescript public constructor( hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions, ) { super(new QRCodeReader(), hints, options); } ``` -------------------------------- ### createBinaryBitmapFromMediaElem static method Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Creates a BinaryBitmap from a media element by first creating a canvas from it and then converting that canvas to a binary bitmap. ```typescript public static createBinaryBitmapFromMediaElem(mediaElement: HTMLVisualMediaElement): BinaryBitmap { const canvas = BrowserCodeReader.createCanvasFromMediaElement(mediaElement); return BrowserCodeReader.createBinaryBitmapFromCanvas(canvas); } ``` -------------------------------- ### constructor Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserMultiFormatOneDReader.md Constructor for creating a BrowserMultiFormatOneDReader instance with optional hints and options. ```APIDOC ## constructor(hints?, options?) ### Description Creates a new `BrowserMultiFormatOneDReader` that wraps a `MultiFormatOneDReader` from `@zxing/library` to decode any 1D barcode. ### Signature ```ts public constructor(hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions) ``` ### Parameters - **hints** (`Map<DecodeHintType, any>`) - Optional - Decode hints. Passed to the underlying `MultiFormatOneDReader` constructor and also stored on the base class for the decode call. - **options** (`IBrowserCodeReaderOptions`) - Optional - Timing options. See the configuration documentation. ### Notes - If `hints` are not provided, an undefined value is forwarded to the base class, which defaults to `new Map<DecodeHintType, any>()`. - Restrictions set at construction time apply to the 1D format selection itself. ``` -------------------------------- ### IBrowserCodeReaderOptions interface Source: https://github.com/zxing-js/browser/blob/master/_autodocs/types.md Configuration options accepted by the BrowserCodeReader constructor and all six reader subclasses. Defaults are 500 ms for both delay options and 5000 ms for tryPlayVideoTimeout. ```ts export interface IBrowserCodeReaderOptions { /** Delay time between subsequent successful decode results. */ delayBetweenScanSuccess?: number; /** Delay time between decode attempts made by the scanner. */ delayBetweenScanAttempts?: number; /** Timeout for waiting the video 'canplay' event. */ tryPlayVideoTimeout?: number; } ``` -------------------------------- ### Import BrowserMultiFormatOneDReader Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserMultiFormatOneDReader.md Import the BrowserMultiFormatOneDReader class from the @zxing/browser package. ```typescript import { BrowserMultiFormatOneDReader } from '@zxing/browser'; ``` -------------------------------- ### createCaptureCanvas static method Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Creates an HTMLCanvasElement sized to the media element's dimensions. Throws ArgumentException if no media element is provided, and Error if not running in a browser document. ```typescript public static createCaptureCanvas(mediaElement: HTMLVisualMediaElement): HTMLCanvasElement { if (!mediaElement) { throw new ArgumentException('Cannot create a capture canvas without a media element.'); } if (typeof document === 'undefined') { throw new Error('The page "Document" is undefined, make sure you\'re running in a browser.'); } const canvasElement = document.createElement('canvas'); const { width, height } = BrowserCodeReader.getMediaElementDimensions(mediaElement); canvasElement.style.width = width + 'px'; canvasElement.style.height = height + 'px'; canvasElement.width = width; canvasElement.height = height; return canvasElement; } ``` -------------------------------- ### prepareVideoElement Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Resolves a video element like createVideoElement and sets autoplay, muted, and playsinline attributes for iOS 11 compatibility. ```APIDOC ## prepareVideoElement ### Description Resolves a video element like createVideoElement and sets the autoplay, muted, and playsinline attributes (autoplay workaround for iOS 11). ### Method static ### Signature `public static prepareVideoElement(videoElem?: HTMLVideoElement | string): HTMLVideoElement` ### Parameters #### Parameters - **videoElem** (HTMLVideoElement | string) - Optional - An existing video element or a DOM id. If undefined, a new video element is created. ### Returns - **HTMLVideoElement** - The prepared video element with attributes set. ``` -------------------------------- ### prepareImageElement Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Resolves an HTMLImageElement from an existing element, a DOM id, or creates a new 200x200 image element. Throws if no usable source is provided. ```APIDOC ## prepareImageElement ### Description Resolves an HTMLImageElement. If a string is provided, it is treated as a DOM id and resolved via getMediaElement. If undefined, a new 200x200 image element is created. Throws an Error if no usable source is provided. ### Method static ### Signature `public static prepareImageElement(imageSource?: HTMLImageElement | string): HTMLImageElement` ### Parameters #### Parameters - **imageSource** (HTMLImageElement | string) - Optional - An existing img element, or a DOM id. If undefined, a new 200x200 img element is created. ### Returns - **HTMLImageElement** - The resolved or created image element. ### Throws - **ArgumentException** - Via getMediaElement for a non-matching id. - **Error** - When nothing usable was passed and document is undefined. ``` -------------------------------- ### createCanvasFromMediaElement static method Source: https://github.com/zxing-js/browser/blob/master/_autodocs/api-reference/BrowserCodeReader-static.md Creates a canvas from a media element by calling createCaptureCanvas and drawing the media frame onto it. Throws Error if the 2D context is unavailable. ```typescript public static createCanvasFromMediaElement(mediaElement: HTMLVisualMediaElement) { const canvas = BrowserCodeReader.createCaptureCanvas(mediaElement); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error('Couldn\'t find Canvas 2D Context.'); } BrowserCodeReader.drawImageOnCanvas(ctx, mediaElement); return canvas; } ```