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

Package detail

html5-qrcode

mebjas559kApache-2.02.3.8TypeScript support: included

A cross platform HTML5 QR Code & bar code scanner

html5, qrcode, html, camera, scanner, barcode, barcode 1d, barcode 2d

readme

Html5-QRCode

Lightweight & cross platform QR Code and Bar code scanning library for the web

Use this lightweight library to easily / quickly integrate QR code, bar code, and other common code scanning capabilities to your web application.

Key highlights

Supports two kinds of APIs

  • Html5QrcodeScanner — End-to-end scanner with UI, integrate with less than ten lines of code.

  • Html5Qrcode — Powerful set of APIs you can use to build your UI without worrying about camera setup, handling permissions, reading codes, etc.

Support for scanning local files on the device is a new addition and helpful for the web browser which does not support inline web-camera access in smartphones. Note: This doesn't upload files to any server — everything is done locally.

CircleCI GitHub issues GitHub tag (latest by date) GitHub Codacy Badge Gitter

GitHub all releases npm

Demo at scanapp.org Demo at qrcode.minhazav.dev - Scanning different types of codes

We need your help!

image Help incentivise feature development, bug fixing by supporting the sponsorhip goals of this project. See list of sponsered feature requests here.

ko-fi

Documentation

The documentation for this project has been moved to scanapp.org/html5-qrcode-docs.

Supported platforms

We are working continuously on adding support for more and more platforms. If you find a platform or a browser where the library is not working, please feel free to file an issue. Check the demo link to test it out.

Legends

  • Means full support — inline webcam and file based
  • Means partial support — only file based, webcam in progress

PC / Mac

Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
Edge
Edge

Android

Chrome
Chrome
Firefox
Firefox
Edge
Edge
Opera
Opera
Opera-Mini
Opera Mini
UC
UC

IOS

Safari
Safari
Chrome
Chrome
Firefox
Firefox
Edge
Edge
* *

* Supported for IOS versions >= 15.1

Before version 15.1, Webkit for IOS is used by Chrome, Firefox, and other browsers in IOS and they do not have webcam permissions yet. There is an ongoing issue on fixing the support for iOS - issue/14

Framework support

The library can be easily used with several other frameworks, I have been adding examples for a few of them and would continue to add more.

Html5 VueJs ElectronJs React Lit

Supported Code formats

Code scanning is dependent on Zxing-js library. We will be working on top of it to add support for more types of code scanning. If you feel a certain type of code would be helpful to have, please file a feature request.

Code Example
QR Code
AZTEC
CODE_39
CODE_93
CODE_128
ITF
EAN_13
EAN_8
PDF_417
UPC_A
UPC_E
DATA_MATRIX
MAXICODE*
RSS_14*
RSS_EXPANDED*

*Formats are not supported by our experimental integration with native BarcodeDetector API integration (Read more).

Description - View Demo

See an end to end scanner experience at scanapp.org.

This is a cross-platform JavaScript library to integrate QR code, bar codes & a few other types of code scanning capabilities to your applications running on HTML5 compatible browser.

Supports:

  • Querying camera on the device (with user permissions)
  • Rendering live camera feed, with easy to use user interface for scanning
  • Supports scanning a different kind of QR codes, bar codes and other formats
  • Supports selecting image files from the device for scanning codes

How to use

Find detailed guidelines on how to use this library on scanapp.org/html5-qrcode-docs.

Demo


Scan this image or visit blog.minhazav.dev/research/html5-qrcode.html

For more information

Check these articles on how to use this library:

Screenshots

screenshot
Figure: Screenshot from Google Chrome running on MacBook Pro

Documentation

Find the full API documentation at scanapp.org/html5-qrcode-docs/docs/apis.

Extra optional configuration in start() method

Configuration object that can be used to configure both the scanning behavior and the user interface (UI). Most of the fields have default properties that will be used unless a different value is provided. If you do not want to override anything, you can just pass in an empty object {}.

fps — Integer, Example = 10

A.K.A frame per second, the default value for this is 2, but it can be increased to get faster scanning. Increasing too high value could affect performance. Value >1000 will simply fail.

qrboxQrDimensions or QrDimensionFunction (Optional), Example = { width: 250, height: 250 }

Use this property to limit the region of the viewfinder you want to use for scanning. The rest of the viewfinder would be shaded. For example, by passing config { qrbox : { width: 250, height: 250 } }, the screen will look like:

This can be used to set a rectangular scanning area with config like:

let config = { qrbox : { width: 400, height: 150 } }

This config also accepts a function of type

/**
  * A function that takes in the width and height of the video stream 
* and returns QrDimensions.
* 
* Viewfinder refers to the video showing camera stream.
*/
type QrDimensionFunction =
    (viewfinderWidth: number, viewfinderHeight: number) => QrDimensions;

This allows you to set dynamic QR box dimensions based on the video dimensions. See this blog article for example: Setting dynamic QR box size in Html5-qrcode - ScanApp blog

This might be desirable for bar code scanning.

If this value is not set, no shaded QR box will be rendered and the scanner will scan the entire area of video stream.

aspectRatio — Float, Example 1.777778 for 16:9 aspect ratio

Use this property to render the video feed in a certain aspect ratio. Passing a nonstandard aspect ratio like 100000:1 could lead to the video feed not even showing up. Ideal values can be: | Value | Aspect Ratio | Use Case | | ----- | ------------ | -------- | |1.333334 | 4:3 | Standard camera aspect ratio | |1.777778 | 16:9 | Full screen, cinematic | |1.0 | 1:1 | Square view |

If you do not pass any value, the whole viewfinder would be used for scanning. Note: this value has to be smaller than the width and height of the QR code HTML element.

disableFlip — Boolean (Optional), default = false

By default, the scanner can scan for horizontally flipped QR Codes. This also enables scanning QR code using the front camera on mobile devices which are sometimes mirrored. This is false by default and I recommend changing this only if:

  • You are sure that the camera feed cannot be mirrored (Horizontally flipped)
  • You are facing performance issues with this enabled.

Here's an example of a normal and mirrored QR Code | Normal QR Code | Mirrored QR Code | | ----- | ---- | | |
|

rememberLastUsedCamera — Boolean (Optional), default = true

If true the last camera used by the user and weather or not permission was granted would be remembered in the local storage. If the user has previously granted permissions — the request permission option in the UI will be skipped and the last selected camera would be launched automatically for scanning.

If true the library shall remember if the camera permissions were previously granted and what camera was last used. If the permissions is already granted for "camera", QR code scanning will automatically * start for previously used camera.

supportedScanTypes - Array<Html5QrcodeScanType> | []

This is only supported for Html5QrcodeScanner.

Default = [Html5QrcodeScanType.SCAN_TYPE_CAMERA, Html5QrcodeScanType.SCAN_TYPE_FILE]

This field can be used to:

  • Limit support to either of Camera or File based scan.
  • Change default scan type.

How to use:

function onScanSuccess(decodedText, decodedResult) {
  // handle the scanned code as you like, for example:
  console.log(`Code matched = ${decodedText}`, decodedResult);
}

let config = {
  fps: 10,
  qrbox: {width: 100, height: 100},
  rememberLastUsedCamera: true,
  // Only support camera scan type.
  supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA]
};

let html5QrcodeScanner = new Html5QrcodeScanner(
  "reader", config, /* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess);

For file based scan only choose:

supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_FILE]

For supporting both as it is today, you can ignore this field or set as:

supportedScanTypes: [
  Html5QrcodeScanType.SCAN_TYPE_CAMERA,
  Html5QrcodeScanType.SCAN_TYPE_FILE]

To set the file based scan as defult change the order:

supportedScanTypes: [
  Html5QrcodeScanType.SCAN_TYPE_FILE,
  Html5QrcodeScanType.SCAN_TYPE_CAMERA]

showTorchButtonIfSupported - boolean | undefined

This is only supported for Html5QrcodeScanner.

If true the rendered UI will have button to turn flash on or off based on device + browser support. The value is false by default.

Scanning only specific formats

By default, both camera stream and image files are scanned against all the supported code formats. Both Html5QrcodeScanner and Html5Qrcode classes can be configured to only support a subset of supported formats. Supported formats are defined in enum Html5QrcodeSupportedFormats.

enum Html5QrcodeSupportedFormats {
  QR_CODE = 0,
  AZTEC,
  CODABAR,
  CODE_39,
  CODE_93,
  CODE_128,
  DATA_MATRIX,
  MAXICODE,
  ITF,
  EAN_13,
  EAN_8,
  PDF_417,
  RSS_14,
  RSS_EXPANDED,
  UPC_A,
  UPC_E,
  UPC_EAN_EXTENSION,
}

I recommend using this only if you need to explicitly omit support for certain formats or want to reduce the number of scans done per second for performance reasons.

Scanning only QR code with Html5Qrcode

const html5QrCode = new Html5Qrcode(
  "reader", { formatsToSupport: [ Html5QrcodeSupportedFormats.QR_CODE ] });
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
    /* handle success */
};
const config = { fps: 10, qrbox: { width: 250, height: 250 } };

// If you want to prefer front camera
html5QrCode.start({ facingMode: "user" }, config, qrCodeSuccessCallback);

Scanning only QR code and UPC codes with Html5QrcodeScanner

function onScanSuccess(decodedText, decodedResult) {
  // Handle the scanned code as you like, for example:
  console.log(`Code matched = ${decodedText}`, decodedResult);
}

const formatsToSupport = [
  Html5QrcodeSupportedFormats.QR_CODE,
  Html5QrcodeSupportedFormats.UPC_A,
  Html5QrcodeSupportedFormats.UPC_E,
  Html5QrcodeSupportedFormats.UPC_EAN_EXTENSION,
];
const html5QrcodeScanner = new Html5QrcodeScanner(
  "reader",
  {
    fps: 10,
    qrbox: { width: 250, height: 250 },
    formatsToSupport: formatsToSupport
  },
  /* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess);

Experimental features

The library now supports some experimental features which are supported in the library but not recommended for production usage either due to limited testing done or limited compatibility for underlying APIs used. Read more about it here. Some experimental features include:

How to modify and build

  1. Code changes should only be made to /src only.

  2. Run npm install to install all dependencies.

  3. Run npm run-script build to build JavaScript output. The output JavaScript distribution is built to /dist/html5-qrcode.min.js. If you are developing on Windows OS, run npm run-script build-windows.

  4. Testing

    • Run npm test
    • Run the tests before sending a pull request, all tests should run.
    • Please add tests for new behaviors sent in PR.
  5. Send a pull request

    • Include code changes only to ./src. Do not change ./dist manually.
    • In the pull request add a comment like
      @all-contributors please add @mebjas for this new feature or tests
      • For calling out your contributions, the bot will update the contributions file.
    • Code will be built & published by the author in batches.

How to contribute

You can contribute to the project in several ways:

  • File issue ticket for any observed bug or compatibility issue with the project.
  • File feature request for missing features.
  • Take open bugs or feature request and work on it and send a Pull Request.
  • Write unit tests for existing codebase (which is not covered by tests today). Help wanted on this - read more.

Support 💖

This project would not be possible without all of our fantastic contributors and sponsors. If you'd like to support the maintenance and upkeep of this project you can donate via GitHub Sponsors.

Sponsor the project for priortising feature requests / bugs relevant to you. (Depends on scope of ask and bandwidth of the contributors).

webauthor@ ben-gy bujjivadu

Help incentivise feature development, bug fixing by supporting the sponsorhip goals of this project. See list of sponsered feature requests here.

Also, huge thanks to following organizations for non monitery sponsorships

Credits

The decoder used for the QR code reading is from Zxing-js https://github.com/zxing-js/library

changelog

Version 2.3.8

Sponsors Huge thanks to supporters of the mission who sponsored the project (See Leaderboard).

  • Jari
  • Dave from Gravity Wiz

See the sponsorship page at ko-fi.

Version 2.3.7

  • Fix QR code scanning error.

Version 2.3.6

  • Fix to minified js, some UI fixes to improve accessibility & SEO.

Version 2.3.5

Multiple bug fixes

Version 2.3.4

  • useBarCodeDetectorIfSupported defaults to true and if supported the library will internally alternate between BarcodeDetector and zxing-js. Same robustness added for file based scan as well if more than one decoder is supported.
  • Fixed the UI issue - Issue#613.
  • Fix for torch issue - Issue#634.
  • In case of scanFile(..) APIs, scan at image resolution. Show Loading image... while the image is being loaded for rendering. More info at Issue#612

Version 2.3.3

Quick fix for - issue#621. With this zoom & torch is not supported in firefox for now.

Version 2.3.2

Features or bug fixes.

  • Hide margin of parent container when camera selection UI is hidden (if only 1 camera is found.) - Issue#599, PR#607 by adamwolf@.

Support for zoom slider in Html5QrcodeScanner. Added basic support for zoom feature under configuration flag (not enabled by default). This was raised in issue issue#330.This should help address some focus issues raised so far.

Not supported on Safari or any IOS browser though!

How to use

let html5QrcodeScanner = new Html5QrcodeScanner(
    "reader", 
    { 
        fps: 10,
        qrbox: qrboxFunction,
        useBarCodeDetectorIfSupported: true,
        rememberLastUsedCamera: true,
        aspectRatio: 4/3,
        showTorchButtonIfSupported: true,
        showZoomSliderIfSupported: true,
        defaultZoomValueIfSupported: 2
        // ^ this means by default camera will load at 2x zoom.
    });

Tech debts

  • Refactored the camera components out of src/html5-qrcode.ts

Version 2.3.1

  • Improved support for UPC types - by Breno1288, forked from PR - pull#501
  • Fix form submission in Firefox issue - Discussion#413 by Joggel72, forked from PR - pull#431
  • Fix support for UPC-E as called out in several bugs - parent issue#605
  • Add willReadFrequently attribute to canvas context for camera scan as per Google Chrome recommendation.

Version 2.3.0

  • Added support for drag and drop of image in file based scanner.
  • Info UI updated.

Version 2.2.8

Custom camera labels when not available.

In certain browsers as well as cases like Android Webview it looks like camera name is not returned by the browser. In such cases the camera selection has empty named options.

To make the UX better, the library will give custom names to the cameras.

For example in Duck Duck Go browser which has this behavior, it will look like this

Before selection After selection
Screenshot_20221105-005544 Screenshot_20221105-005550

Version 2.2.7

Add support for custom CSS

Developer / User Story: As a developer I can write custom CSS for Html5QrcodeScanner.

Feature request: Issue#389

List of CSS class and IDs added.

  1. All key elements will have a common CSS class html5-qrcode-element. This way developers can customise element by element. For example:
button.html5-qrcode-element {
    color: 'red';
    border: '1px solid red';
}

Key elements are:

  • Request camera permission button.
  • "Scan and image file" vs "Scan using camera directly" link.
  • "File selection" input ('file')
  • Start or Stop camera button.
  • Camera selection Select element
  • Torch button

  • key elements will have specific IDs defined in src/ui/scanner/base.ts. This can be used to customise per elements.

TODOs
  • <input disabled="" type="checkbox"> Document in a blog post
  • <input disabled="" type="checkbox"> Add pointer in qrcode.minhazav.dev
  • <input disabled="" type="checkbox"> Add pointer in Readme

Change file selection UI from input to button

Modified the UI a little to hide the file selection as input and replace with custom button and javascript based solution.

One motivation here is this will allow more uniform style for the widget.

Graduate useBarCodeDetectorIfSupported to Html5QrcodeConfigs.

useBarCodeDetectorIfSupported was tested as an experimental configuration for a long time and has proven to be very efficient and well supported. It has been tested in ScanApp for quiet some time.

Considering this experimental API is not well documented, it makes it hard for folks to discover it. By graduating this configuration to Html5QrcodeConfigs I hope to make it more discoverable.

In this version the ExperimentalFeaturesConfig#useBarCodeDetectorIfSupported has been marked deprecated but not removed due to backwards compatibility reasons. Users can set either of them but Html5QrcodeConfigs one will take precedence if set.

Once further support is added to browsers, this can be set as true by default.

Version 2.2.5 & Version 2.2.6

Small minification fix in Version 2.2.6.

Added support for turning torch On and Off in Html5QrcodeScanner.

On supported devices + browsers.

This new feature will implement the feature request - Issue#129 and add support for torch (also called flash) on supported devices and browsers.

So far I have confirmed functionality on Samsung Flip 4 Chrome and Internet (Samsung's default browser).

This is only supported on Html5QrcodeScanner and can be enabled using the config like this.

let html5QrcodeScanner = new Html5QrcodeScanner(
    "reader", 
    { 
        fps: 10,
        qrbox: qrboxFunction,
        // Important notice: this is experimental feature, use it at your
        // own risk. See documentation in
        // mebjas@/html5-qrcode/src/experimental-features.ts
        experimentalFeatures: {
            useBarCodeDetectorIfSupported: true
        },
        rememberLastUsedCamera: true,
        aspectRatio: 1.7777778,
        showTorchButtonIfSupported: true
    });

The showTorchButtonIfSupported: true part is the crucial one. It's off by default for now as I don't like the UI very much.

Added support for getRunningTrackSettings().

Added a new API to get settings (type: MediaTrackSettings) for running video streams while QR code is being scanned.

/**
 * Returns the object containing the current values of each constrainable
 * property of the running video track.
 * 
 * Read more: https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/getSettings
 * 
 * Important:
 *  1. Must be called only if the camera based scanning is in progress.
 *
 * @returns the supported settings of the running video track.
 * @throws error if the scanning is not in running state.
 */
public getRunningTrackSettings(): MediaTrackSettings {}

This API can be used to check the currently applied settings on the running video stream like weather torch is on or not.

getRunningTrackCapabilities(..) and applyVideoConstraints(..) out of beta.

Both Html5Qrcode and Html5QrcodeScanner classes had support for following APIs.

/**
 * Returns the capabilities of the running video track.
 * 
 * Read more: https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/getConstraints
 * 
 * Important:
 *  1. Must be called only if the camera based scanning is in progress.
 *
 * @returns the capabilities of a running video track.
 * @throws error if the scanning is not in running state.
 */
public getRunningTrackCapabilities(): MediaTrackCapabilities {}

/**
 * Apply a video constraints on running video track from camera.
 *
 * Important:
 *  1. Must be called only if the camera based scanning is in progress.
 *  2. Changing aspectRatio while scanner is running is not yet supported.
 *
 * @param {MediaTrackConstraints} specifies a variety of video or camera
 *  controls as defined in
 *  https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints
 * @returns a Promise which succeeds if the passed constraints are applied,
 *  fails otherwise.
 * @throws error if the scanning is not in running state.
 */
public applyVideoConstraints(videoConstaints: MediaTrackConstraints)
    : Promise<any> {}

These have now been taken out of beta and publicly documented. More blog articles to be published for these.

Sponsorship

Thanks for sponsorship!

Version 2.2.4

Version 2.2.1

  • Added support for supportedScanType in Html5QrcodeScanner. This feature was implemented by our latest contributor - mohsinaav@

    Now users can decide to only use camera based scan or file based scan or use them in different order. How to use:

    function onScanSuccess(decodedText, decodedResult) {
        // handle the scanned code as you like, for example:
        console.log(`Code matched = ${decodedText}`, decodedResult);
    }

    let config = {
        fps: 10,
        qrbox: {width: 100, height: 100},
        rememberLastUsedCamera: true,
        // Only support camera scan type.
        supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA]
    };

    let html5QrcodeScanner = new Html5QrcodeScanner(
        "reader", config, /* verbose= */ false);
    html5QrcodeScanner.render(onScanSuccess);

For file based scan only choose:

   supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_FILE]

For supporting both as it is today, you can ignore this field or set as:

   supportedScanTypes: [
       Html5QrcodeScanType.SCAN_TYPE_CAMERA,
        Html5QrcodeScanType.SCAN_TYPE_FILE]

To set the file based scan as defult change the order:

      supportedScanTypes: [
        Html5QrcodeScanType.SCAN_TYPE_FILE,
        Html5QrcodeScanType.SCAN_TYPE_CAMERA]

Version 2.2.0

  • config.qrbox now supports consuming function of type

    /**
     * A function that takes in the width and height of the video stream 
    * and returns QrDimensions.
    * 
    * Viewfinder refers to the video showing camera stream.
    */
    export type QrDimensionFunction =
        (viewfinderWidth: number, viewfinderHeight: number) => QrDimensions;

    This will allow developers to define custom QR box dimensions for their implementations.

    Example:

    function onScanSuccess(decodedText, decodedResult) {
        // handle the scanned code as you like, for example:
        console.log(`Code matched = ${decodedText}`, decodedResult);
    }
    
    // Square QR box with edge size = 70% of the smaller edge of the viewfinder.
    let qrboxFunction = function(viewfinderWidth, viewfinderHeight) {
        let minEdgePercentage = 0.7; // 70%
        let minEdgeSize = Math.min(viewfinderWidth, viewfinderHeight);
        let qrboxSize = Math.floor(minEdgeSize * minEdgePercentage);
        return {
            width: qrboxSize,
            height: qrboxSize
        };
    }
    
    let html5QrcodeScanner = new Html5QrcodeScanner(
        "reader",
        { fps: 10, qrbox: qrboxFunction },
        /* verbose= */ false);
    html5QrcodeScanner.render(onScanSuccess);

Version 2.1.6

  • Add alt information to info icon to improve accessibility.

Version 2.1.5

  • Changed behavior from throwing error in case qrbox.width or qrbox is larger than the width of the root element. In such cases the dimension will automatically be truncated to the size of root element and will throw a warning based on verbosity settings. This should address issue#357
  • If qrbox is not set in config for either Html5QrcodeScanner or Html5Qrcode the scanning box will default to the size of video stream. From UI perspective there will be no shaded QR scanning box visible to user. This should resolve Issue#343.
  • Calling Html5QrcodeScanner#clear() will also clear the UI rendered due to image based scan. This should address issue#193

Version 2.1.4

Huge thanks to Ben Richardson for one time sponsorship!!

This is helpful in keeping the project in shape! Cheers to you!!

See sponsorship dashboard

Changelog

  • Fix bug in stop() method in Html5Qrcode class.
  • Fix a minor UI error, where error message shown due to a certain camera not working, is not hidden when a functional camera is selected.
  • Feature Request#356 - Freeze the image (not clear) on success.

Now calling html5qrcode.pause(/* shouldPauseVideo */ true) or html5qrcodeScanner.pause(/* shouldPauseVideo */ true) will freeze the viewfinder and calling corresponding resume() will unfreeze the viewfinder. Calling with false or no argument will just pause scanning without effecting the viewfinder.

Version 2.1.3

  • Reduce the assets size using SVG instead of GIF files.

Version 2.1.2

  • If there is only one camera detected, automatically use that.
  • Cosmetic fixes: show Launching Camera... in button when launching the camera.

Version 2.1.1

  • Fixed dashboard section exceeding the parent HTML element width.
  • Added support for following beta APIs which allows modifying running video stream state, which camera stream is running.

    /**
     * Returns the capabilities of the running video track.
     * 
     * Note: Should only be called if {@code Html5QrcodeScanner#getState()}
     *   returns {@code Html5QrcodeScannerState#SCANNING} or 
     *   {@code Html5QrcodeScannerState#PAUSED}.
     *
     * @beta This is an experimental API
     * @returns the capabilities of a running video track.
     * @throws error if the scanning is not in running state.
     */
    public getRunningTrackCapabilities(): MediaTrackCapabilities;
    
    /**
     * Apply a video constraints on running video track from camera.
     *
     * Note: Should only be called if {@code Html5QrcodeScanner#getState()}
     *   returns {@code Html5QrcodeScannerState#SCANNING} or 
     *   {@code Html5QrcodeScannerState#PAUSED}.
     *
     * @beta This is an experimental API
     * @param {MediaTrackConstraints} specifies a variety of video or camera
     *  controls as defined in
     *  https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints
     * @returns a Promise which succeeds if the passed constraints are applied,
     *  fails otherwise.
     * @throws error if the scanning is not in running state.
     */
    public applyVideoConstraints(videoConstaints: MediaTrackConstraints)   

    Important note: Both these APIs are beta and not publicly documented.

  • Support for pausing and resuming code scanning in camera scan mode. New APIs are added to both Html5QrcodeScanner and Html5Qrcode. They should only be called when the scanner state is Html5QrcodeScannerState#SCANNING (== 2) or Html5QrcodeScannerState#PAUSED (== 3).

    APIs added:

    /**
     * Pauses the ongoing scan.
     * 
     * Note: this will not stop the viewfinder, but stop decoding camera stream.
     * 
     * @throws error if method is called when scanner is not in scanning state.
     */
    public pause();
    
    /**
     * Resumes the paused scan.
     * 
     * Note: with this caller will start getting results in success and error
     * callbacks.
     * 
     * @throws error if method is called when scanner is not in paused state.
     */
    public resume();
    
        /**
     * Gets state of the camera scan.
     *
     * @returns state of type {@enum ScannerState}.
     */
    public getState(): Html5QrcodeScannerState;

    Example usage:

    `js let html5QrcodeScanner = new Html5QrcodeScanner(

    "reader", 
    { 
        fps: 10,
        qrbox: {width: 250, height: 250},
        rememberLastUsedCamera: true,
        aspectRatio: 1.7777778
    });

    function onScanSuccess(decodedText, decodedResult) {

    if (html5QrcodeScanner.getState() 
        !== Html5QrcodeScannerState.NOT_STARTED) {
        // Add this check to ensure success callback is not being called
        // from file based scanner.
    
        // Pause on scan result
        html5QrcodeScanner.pause();
    }
    // Handle your business logic
    // ...

    // .. ok to resume now or elsewhere.
    // just call html5QrcodeScanner.resume();
    // Make sure to check if the state is !== NOT_STARTED
}
html5QrcodeScanner.render(onScanSuccess);
```

Note: when camera scan is paused it adds a UI element indicating that state.

Version 2.1.0

Version 2.0.13

Added ability to set custom width and height to the scanner with config.qrbox argument.

Now we can pass config.qrbox argument as instance of interface QrDimensions.

function onScanSuccess(decodedText, decodedResult) { /* handle success. */ }
function onScanFailure(error) { /* handle failure. */ }

let config = { fps: 10, qrbox: { width: 250, height: 250 } };

let html5QrcodeScanner = new Html5QrcodeScanner(
    "reader", config , /* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess, onScanFailure);

For a rectangular QR Scanning box we can set it to something like:

// .. rest of the code
let config = { fps: 10, qrbox: { width: 400, height: 150 } };

let html5QrcodeScanner = new Html5QrcodeScanner(
    "reader", config , /* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess, onScanFailure);

Version 2.0.12

  • Redundant information in the top status bar removed.
  • Added support for remembering permission and last camera used. This feature is on by default. Can be turned on or off using rememberLastUsedCamera flag in Html5QrcodeScannerConfig. How to explicitly enable it:
      function onScanSuccess(decodedText, decodedResult) {
          // handle success.
      }
      let html5QrcodeScanner = new Html5QrcodeScanner(
        "reader", 
        { 
            fps: 10,
            qrbox: 250,
            rememberLastUsedCamera: true
            // ^ set this to false to disable this.
        });
      html5QrcodeScanner.render(onScanSuccess);

Version 2.0.11

  • Add support for native BarcodeDetector based scanning.
    • On Chrome ZXing based decoder takes 20-25 ms on my Mac book pro 16.
    • On Chrome BarcodeDetector based decoder takes 8.6-11 ms on my Mac book pro 16.
      // How to enable
      // Note: will only work if browser / OS supports this HTML api.
      // Read more: https://developer.mozilla.org/en-US/docs/Web/API/BarcodeDetector#browser_compatibility
      function onScanSuccess(decodedText, decodedResult) {
        // handle success.
      }
      let html5QrcodeScanner = new Html5QrcodeScanner(
      "reader", 
      { 
          fps: 10,
          qrbox: 250,
          experimentalFeatures: {
              useBarCodeDetectorIfSupported: true
          }
      });
      html5QrcodeScanner.render(onScanSuccess);

Version 2.0.10

  • Migrate from assets hosted on Github to embedded base64 assets.

Version 2.0.9

Version 2.0.8

  • Added support for configuring supported formats in Html5Qrcode & Html5QrcodeScanner.

Version 2.0.6

  • Issue#211 fixed - swapped text for file based scanning and camera scanning during typescript migration.

Version 2.0.5

  • Issue#202 fixed - error logs dumped to console even if verbose flag is not set in Html5Qrcode.

Version 2.0.4

  • Source code migrated from javascript to typescript.
  • Issue#198 fixed - Fixing autoplay in Cordova Android apps

Version 2.0.3

  • Show specific error messages if web-cam access fails due to insecure contexts like web page being neither https or localhost.

Version 2.0.2

Version 2.0.1

Version 2.0.0

  • Major Change Migrated from Lazarsoft QR Code scanning to ZXing-js.
    • More robust support for QR Code scanning
    • Support for barcode scanning in the following formats
       ZXing.BarcodeFormat.QR_CODE,
       ZXing.BarcodeFormat.AZTEC,
       ZXing.BarcodeFormat.CODABAR,
       ZXing.BarcodeFormat.CODE_39,
       ZXing.BarcodeFormat.CODE_93,
       ZXing.BarcodeFormat.CODE_128,
       ZXing.BarcodeFormat.DATA_MATRIX,
       ZXing.BarcodeFormat.MAXICODE,
       ZXing.BarcodeFormat.ITF,
       ZXing.BarcodeFormat.EAN_13,
       ZXing.BarcodeFormat.EAN_8,
       ZXing.BarcodeFormat.PDF_417,
       ZXing.BarcodeFormat.RSS_14,
       ZXing.BarcodeFormat.RSS_EXPANDED,
       ZXing.BarcodeFormat.UPC_A,
       ZXing.BarcodeFormat.UPC_E,
       ZXing.BarcodeFormat.UPC_EAN_EXTENSION
    • Library size increased to 319Kb.

Version 1.2.3

  • Added support for videoConstraints in config as an experimental config.

         /* videoConstraints: {MediaTrackConstraints}, Optional
          *  @beta(this config is not well supported yet).
          *
          *  Important: When passed this will override other configurations
          *  like 'cameraIdOrConfig' or configurations like 'aspectRatio'.
          *
          *  videoConstraints should be of type {@code MediaTrackConstraints}
          *  as defined in
          *  https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints
          *  and is used to specify a variety of video or camera controls
          *  like: aspect ratio, facing mode, video frame rate.
          */

    If passed this will override cameraIdOrConfig and aspectRatio.

  • Added two new experimental APIs in Html5Qrcode class

    • getRunningTrackCapabilities() - New

        /**
         * Returns the capabilities of the running video track.
         * 
         * @beta This is an experimental API
         * @returns the capabilities of a running video track.
         * @throws error if the scanning is not in running state.
         */
        getRunningTrackCapabilities() {}
    • applyVideoConstraints(videoConstaints) - New

        /**
         * Apply a video constraints on running video track.
         * 
         * Important:
         *  1. Must be called only if the camera based scanning is in progress.
         *  2. Changing aspectRatio while scanner is running is not yet supported.
         * 
         * @beta This is an experimental API
         * @param {MediaTrackConstraints} specifies a variety of video or camera
         *  controls as defined in 
         *  https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints
         * @returns a Promise which succeeds if the passed constraints are applied,
         *  fails otherwise.
         * @throws error if the scanning is not in running state.
         */
        applyVideoConstraints(videoConstaints) {}

Version 1.2.2

  • Bug fix in Html5QrcodeScanner - file scanning.

Version 1.2.1

  • Added support for facingMode constraing in Html5Qrcode#start

Update: In mobile devices you may want users to directly scan the QR code using the back camera or the front camera for some use cases. For such cases you can avoid using the exact camera device id that you get from Html5Qrcode.getCameras(). The start() method allows passing constraints in place of camera device id similar to html5 web API syntax. You can start scanning like mentioned in these examples:

const html5QrCode = new Html5Qrcode("#reader");
const qrCodeSuccessCallback = message => { /* handle success */ }
const config = { fps: 10, qrbox: 250 };

// If you want to prefer front camera
html5QrCode.start({ facingMode: "user" }, config, qrCodeSuccessCallback);

// If you want to prefer back camera
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback);

// Select front camera or fail with `OverconstrainedError`.
html5QrCode.start({ facingMode: { exact: "user"} }, config, qrCodeSuccessCallback);

// Select back camera or fail with `OverconstrainedError`.
html5QrCode.start({ facingMode: { exact: "environment"} }, config, qrCodeSuccessCallback);

Version 1.2.0

  • Added support for scanning mirrored QR code, or scanning in case camera feed is mirrored (horizontally flipped).

Version 1.1.9

  • Added support for config.aspectRatio in both Html5Qrcode and Html5QrcodeScanner

    Use this property to render the video feed in a certain aspect ratio. Passing a nonstandard aspect ratio like 100000:1 could lead to the video feed not even showing up. Ideal values can be: | Value | Aspect Ratio | Use Case | | ----- | ------------ | -------- | |1.333334 | 4:3 | Standard camera aspect ratio | |1.777778 | 16:9 | Fullscreen, cinematic | |1.0 | 1:1 | Square view |

Version 1.1.8

  • Bug fix on Html5QrcodeScanner#clear()

Version 1.1.7

  • Html5QrcodeScanner#clear() returns a Promise.

Version 1.1.6

  • Bug fixes
    • #74 - state errors on file based scanning.

Version 1.1.0

  • Added support for a full scanner with end to end UI - Html5QrcodeScanner

Version 1.0.9

  • Fixed issue #41
  • Added support for verbose logging in the library as a constructor argument.

Version 1.0.8

  • Added support for realtime feedbacks on viewfinder for inline scanning |Platform|Screenshot| |------|-----------| |On PC | | |On Android||

Version 1.0.7

  • Fixed the video size issue in #21
  • Removed fixed height of viewfinder, now the height is based on the video stream. The width is honored if the input element has a default width. Otherwise default width is applied.
  • If config.qrbox is greater than derived height, the config is ignored & no shading is applied.
  • The sequence of steps have changed
    • First we get the video feed from the selected camera
    • Then we render video
    • Then based on the height of the video we set the canvas and start scanning.
  • For file scanning, if the container element has some height or width both are honored. Otherwise default width is applied and height is derived from the image.

Older versions

Mostly covered in readme, changelog tracking started since version 1.0.7