How can an LWC in the Field Service mobile app use device features such as the barcode scanner?
Answer
Use the Lightning Mobile Capabilities module, lightning/mobileCapabilities, inside an LWC. It exposes native features such as the barcode scanner, location service, NFC and document scanner.
javascript
import { LightningElement } from 'lwc';
import { getBarcodeScanner } from 'lightning/mobileCapabilities';
export default class ScanPart extends LightningElement {
scanner;
code;
connectedCallback() {
this.scanner = getBarcodeScanner();
}
async handleScan() {
if (this.scanner && this.scanner.isAvailable()) {
const result = await this.scanner.beginCapture({
barcodeTypes: [this.scanner.barcodeTypes.QR]
});
this.code = result.value;
this.scanner.endCapture();
}
}
}
Key points
- Always call
isAvailable(). These APIs only work in the native mobile app, not in a desktop browser. - Provide a fallback, such as a manual input field.
- Handle errors and user cancellation.
LWCMobileBarcodemobileCapabilities