Newer Version Available

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

BarcodeScanner Example—Single Scan (Legacy)

Here’s a minimal but complete example of a Lightning web component that uses BarcodeScanner to recognize a barcode.

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

The HTML template provides the bare minimum for a scanning user interface. There’s an element to display the results of a scan, a bit of static help text, and a button to start a scan. The only thing mildly interesting is the use of the disabled attribute to disable the scan button when not on a mobile device. This attribute is set based on the results of isAvailable() when the component is initialized.

1<!-- barcodeScannerExample.html -->
2<template>
3    <div class="slds-text-align_center">
4        <span class="slds-text-heading_large">BarcodeScanner: Single Scan</span>
5    </div>
6
7    <!-- After a barcode is successfully scanned, 
8         its value is displayed here: -->
9    <template lwc:if={scannedBarcode}>
10        <div class="slds-var-m-vertical_large slds-var-p-vertical_medium 
11             slds-text-align_center slds-border_top slds-border_bottom">
12            Scanned barcode value is:
13            <span class="slds-text-heading_small">{scannedBarcode}</span>
14        </div>
15    </template>
16
17    <!-- Static help text -->
18    <div class="slds-text-align_center slds-text-color_weak slds-m-vertical_large">
19        Click <strong>Scan Barcode</strong> to open a barcode scanner camera view. Position a
20        barcode in the scanner view to scan it.
21    </div>
22
23    <!-- The click-to-scan button;
24         Disabled if BarcodeScanner isn't available -->
25    <div class="slds-align_absolute-center slds-m-vertical_large">
26        <lightning-button
27            variant="brand"
28            class="slds-var-m-left_x-small"
29            disabled={scanButtonDisabled}
30            icon-name="utility:scan"
31            label="Scan Barcode"
32            title="Open a camera view and look for a barcode to scan"
33            onclick={handleBeginScanClick}>
34        </lightning-button>
35    </div>
36</template>

This simple example displays the decoded value of a successful scan. It also displays a toast-style message based on the results of the scan. Each phase of the scanning lifecycle writes a console message.

1// barcodeScannerExample.js
2import { LightningElement } from 'lwc';
3import { ShowToastEvent } from 'lightning/platformShowToastEvent';
4import { getBarcodeScanner } from 'lightning/mobileCapabilities';
5
6export default class BarcodeScannerExample extends LightningElement {
7    myScanner;
8    scanButtonDisabled = false;
9    scannedBarcode = '';
10
11    // When component is initialized, detect whether to enable Scan button
12    connectedCallback() {
13        this.myScanner = getBarcodeScanner();
14        if (this.myScanner == null || !this.myScanner.isAvailable()) {
15            this.scanButtonDisabled = true;
16        }
17    }
18
19    handleBeginScanClick(event) {
20        // Reset scannedBarcode to empty string before starting new scan
21        this.scannedBarcode = '';
22
23        // Make sure BarcodeScanner is available before trying to use it
24        // Note: We _also_ disable the Scan button if there's no BarcodeScanner
25        if (this.myScanner != null && this.myScanner.isAvailable()) {
26            const scanningOptions = {
27                barcodeTypes: [this.myScanner.barcodeTypes.QR],
28                instructionText: 'Scan a QR Code',
29                successText: 'Scanning complete.'
30            };
31            this.myScanner
32                .beginCapture(scanningOptions)
33                .then((result) => {
34                    console.log(result);
35
36                    // Do something with the barcode scan value:
37                    // - look up a record
38                    // - create or update a record
39                    // - parse data and put values into a form
40                    // - and so on; this is YOUR code
41                    // Here, we just display the scanned value in the UI
42                    this.scannedBarcode = result.value;
43                    this.dispatchEvent(
44                        new ShowToastEvent({
45                            title: 'Successful Scan',
46                            message: 'Barcode scanned successfully.',
47                            variant: 'success'
48                        })
49                    );
50                })
51                .catch((error) => {
52                    // Handle cancellation and unexpected errors here
53                    console.error(error);
54
55                    if (error.code == 'USER_DISMISSED') {
56                        // User clicked Cancel
57                        this.dispatchEvent(
58                            new ShowToastEvent({
59                                title: 'Scanning Cancelled',
60                                message:
61                                    'You cancelled the scanning session.',
62                                mode: 'sticky'
63                            })
64                        );
65                    }
66                    else { 
67                        // Inform the user we ran into something unexpected
68                        this.dispatchEvent(
69                            new ShowToastEvent({
70                                title: 'Barcode Scanner Error',
71                                message:
72                                    'There was a problem scanning the barcode: ' +
73                                    error.message,
74                                variant: 'error',
75                                mode: 'sticky'
76                            })
77                        );
78                    }
79                })
80                .finally(() => {
81                    console.log('#finally');
82
83                    // Clean up by ending capture,
84                    // whether we completed successfully or had an error
85                    this.myScanner.endCapture();
86                });
87        } else {
88            // BarcodeScanner is not available
89            // Not running on hardware with a camera, or some other context issue
90            console.log(
91                'Scan Barcode button should be disabled and unclickable.'
92            );
93            console.log('Somehow it got clicked: ');
94            console.log(event);
95
96            // Let user know they need to use a mobile phone with a camera
97            this.dispatchEvent(
98                new ShowToastEvent({
99                    title: 'Barcode Scanner Is Not Available',
100                    message:
101                        'Try again from the Salesforce app on a mobile device.',
102                    variant: 'error'
103                })
104            );
105        }
106    }
107}