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}