Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and 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
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
- 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((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 });