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
11      class="slds-var-m-vertical_large slds-var-p-vertical_medium 
12             slds-text-align_center slds-border_top slds-border_bottom"
13    >
14      Scanned barcode value is:
15      <span class="slds-text-heading_small">{scannedBarcode}</span>
16    </div>
17  </template>
18
19  <!-- Static help text -->
20  <div class="slds-text-align_center slds-text-color_weak slds-m-vertical_large">
21    Click <strong>Scan Barcode</strong> to open a barcode scanner camera view. Position a barcode in
22    the scanner view to scan it.
23  </div>
24
25  <!-- The click-to-scan button;
26         Disabled if BarcodeScanner isn't available -->
27  <div class="slds-align_absolute-center slds-m-vertical_large">
28    <lightning-button
29      variant="brand"
30      class="slds-var-m-left_x-small"
31      disabled="{scanButtonDisabled}"
32      icon-name="utility:scan"
33      label="Scan Barcode"
34      title="Open a camera view and look for a barcode to scan"
35      onclick="{handleBeginScanClick}"
36    >
37    </lightning-button>
38  </div>
39</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: "You cancelled the scanning session.",
61                mode: "sticky",
62              }),
63            );
64          } else {
65            // Inform the user we ran into something unexpected
66            this.dispatchEvent(
67              new ShowToastEvent({
68                title: "Barcode Scanner Error",
69                message: "There was a problem scanning the barcode: " + error.message,
70                variant: "error",
71                mode: "sticky",
72              }),
73            );
74          }
75        })
76        .finally(() => {
77          console.log("#finally");
78
79          // Clean up by ending capture,
80          // whether we completed successfully or had an error
81          this.myScanner.endCapture();
82        });
83    } else {
84      // BarcodeScanner is not available
85      // Not running on hardware with a camera, or some other context issue
86      console.log("Scan Barcode button should be disabled and unclickable.");
87      console.log("Somehow it got clicked: ");
88      console.log(event);
89
90      // Let user know they need to use a mobile phone with a camera
91      this.dispatchEvent(
92        new ShowToastEvent({
93          title: "Barcode Scanner Is Not Available",
94          message: "Try again from the Salesforce app on a mobile device.",
95          variant: "error",
96        }),
97      );
98    }
99  }
100}

See Also