Newer Version Available
Use the BarcodeScanner API
To develop a Lightning component with barcode scanning features, use the BarcodeScanner
API.
- Import BarcodeScanner into your component definition to make the BarcodeScanner API functions available to your code.
- Test to make sure BarcodeScanner is available before you call scanning lifecycle functions.
- Use the scanning lifecycle functions to start, continue, and stop scanning.
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.
- Start a scan with scan(options).
- Handle the result of the scan, which is returned in the form of a promise.
- End the scan with dismiss().
For example:
1myScanner.scan(scanningOptions)
2 .then((result) => {
3 // Do something with the result of the scan
4 console.log(result);
5 this.scannedBarcode = result.value;
6 })
7 .catch((error) => {
8 // Handle cancellation and scanning errors here
9 console.error(error);
10 })
11 .finally(() => {
12 myScanner.dismiss();
13 });