Newer Version Available

This content describes an older version of this product. View Latest

Use the BarcodeScanner API

To develop a Lightning component with barcode scanning features, use the BarcodeScanner API.
  1. Import BarcodeScanner into your component definition to make the BarcodeScanner API functions available to your code.
  2. Test to make sure BarcodeScanner is available before you call scanning lifecycle functions.
  3. Use the scanning lifecycle functions to start, continue, and stop scanning.

We recommend using the modern scan() and dismiss() API functions in your LWC scanning code to streamline your development experience. The legacy API functions beginCapture(), resumeCapture(), and endCapture() are still available, but will be retired in a future release. See Understand BarcodeScanner Modern and Legacy APIs for additional details.

Important

Add BarcodeScanner to a Lightning Web Component

In your component’s JavaScript file, import BarcodeScanner using the standard JavaScript import statement. Specifically, import the getBarcodeScanner() factory function from the lightning/mobileCapabilities module, like so:
1import { getBarcodeScanner } from 'lightning/mobileCapabilities';

After it’s imported into your component, use the factory function to get an instance of BarcodeScanner. With your BarcodeScanner instance, use the utility functions and constants to verify scanner availability and to configure scans. Use the scanning lifecycle functions to perform scanning operations.

Test BarcodeScanner Availability

BarcodeScanner depends on physical device hardware and platform features. A component that uses BarcodeScanner renders without errors on a desktop computer, but scanning functions fail. To avoid these errors, test if BarcodeScanner functionality is available before you use it.

1handleBeginScanClick(event) {
2    const myScanner = getBarcodeScanner();
3    if(myScanner.isAvailable()) {
4        // Perform scanning operations
5    }
6    else {
7        // Scanner not available
8        // Not running on hardware with a scanner
9        // Handle with message, error, beep, and so on
10    }
11}

Scan a Barcode

Scanning with BarcodeScanner is simple using the scanning lifecycle functions.
  1. Start a scan with scan(options).
  2. Handle the result of the scan, which is returned in the form of a promise.
  3. End the scan with dismiss().

For example:

1myScanner.scan(scanningOptions)
2    .then((resultsArray) => {
3        // Do something with the result of the scan
4        for (let singleResult in resultsArray) {
5            console.log(singleResult);
6            this.scannedBarcodes.push(singleResult.value);
7        }
8    })
9    .catch((error) => {
10        // Handle cancellation and scanning errors here
11        console.error(error);
12    })
13    .finally(() => {
14        myScanner.dismiss();
15    });
See scan(options) for more details of how to handle scan results, handle errors, and so on.