Salesforce Barcode Scanner LWC

SFDC Coder
4 min readSep 5, 2020

--

Prev. Article: Safe Navigation Operator

Hello Guys,

Today we will talk about one more amazing feature to be released in Winter 21 and that is Barcode Scanning on a Mobile Device (Beta)

** NOTE: This works only on mobile devices.

To develop a Lightning component with barcode scanning features, Salesforce provides BarcodeScanner API. We need to import getBarcodeScanner() factory function from the lightning/mobileCapabilites module in our JS file.

In our component first, we will detect if the scanner is available, If it is not available(Desktop) then our “Scan Barcode” button will be disabled else we will enable it.

Code Snippet:

// When component is initialized, detect whether to enable Scan button
connectedCallback() {
this.myScanner = getBarcodeScanner();
if (this.myScanner == null || !this.myScanner.isAvailable()) {
this.scanButtonDisabled = true;
}
}
View On Desktop (Disabled Button)

Now try to use a mobile phone and open the salesforce app then you will see that “Scan Barcode” button is enabled now.

Full Code Snippet:

HTML File:

*Note: After creating this LWC Component follow the below steps to make it available in the Salesforce mobile app.

  1. Setup -> tabs -> Lightning Component Tabs, create a new tab for this component.

2. Setup -> Salesforce Navigation, then include the newly created tab

3. Choose Mobile Only option

<!-- barcodeScannerExample.html --><template><!-- After a barcode is successfully scanned,its value is displayed here --><divclass="slds-var-m-vertical_large slds-var-p-vertical_mediumslds-text-align_center slds-border_top slds-border_bottom">Scanned barcode value is:<span class="slds-text-heading_small">{scannedBarcode}</span></div><!-- This is static help text --><div class="slds-align_absolute-center slds-text-align_centerslds-text-color_weak">Click Scan Barcode to open a barcode scanner camera view. Position abarcode in the scanner view to scan it.</div><!-- The click-to-scan button;Disabled if BarcodeScanner isn't available --><div class="slds-text-align_center"><lightning-buttonvariant="brand"class="slds-var-m-left_x-small"disabled={scanButtonDisabled}icon-name="utility:cases"label="Scan Barcode"title="Open a camera view and look for a barcode to scan"onclick={handleBeginScanClick}></lightning-button></div></template>handleBeginScanClick(event) {if (this.myScanner != null && this.myScanner.isAvailable()) {
const scanningOptions = {
barcodeTypes: [this.myScanner.barcodeTypes.QR, this.myScanner.barcodeTypes.UPC_E]
};
this.myScanner
.beginCapture(scanningOptions)
.then((result) => {
console.log(result);
// Do some interesting stuff here with the barcode scan value
// like look up a record, create or update a record, parse data and put values into a form etc
// Here, we just display the scanned value in the UI
this.scannedBarcode = decodeURIComponent(result.value);
this.dispatchEvent(
new ShowToastEvent({
title: 'Successful Scan',
message: 'Barcode scanned successfully.',
variant: 'success'
})
);
})
}
}

JS File:

**Note: In JS file we need to provide supported barcodeTypes which you want to use i.e QR, UPC_E, CODE_128, CODE_39, CODE_93, DATA_MATRIX, EAN_13, EAN_8, PDF_417, ITF

Dummy QR code or other codes can be created from link1 and link2

// barcodeScannerExample.jsimport { LightningElement } from 'lwc';import { ShowToastEvent } from 'lightning/platformShowToastEvent';import { getBarcodeScanner } from 'lightning/mobileCapabilities';export default class BarcodeScannerExample extends LightningElement {
myScanner;
scanButtonDisabled = false; scannedBarcode = '';// When component is initialized, detect whether to enable Scan button connectedCallback() { this.myScanner = getBarcodeScanner(); if (this.myScanner == null || !this.myScanner.isAvailable()) { this.scanButtonDisabled = true; } }handleBeginScanClick(event) {// Reset scannedBarcode to empty string before starting new scanthis.scannedBarcode = '';// Make sure BarcodeScanner is available before trying to use it// Note: We _also_ disable the Scan button if there's no BarcodeScannerif (this.myScanner != null && this.myScanner.isAvailable()) {const scanningOptions = { barcodeTypes: [this.myScanner.barcodeTypes.QR, this.myScanner.barcodeTypes.UPC_E]};this.myScanner.beginCapture(scanningOptions).then((result) => { console.log(result); // Here, we just display the scanned value in the UI this.scannedBarcode = decodeURIComponent(result.value); this.dispatchEvent( new ShowToastEvent({ title: 'Successful Scan', message: 'Barcode scanned successfully.', variant: 'success' }) );}).catch((error) => { console.error(error); // Handle unexpected errors here // Inform the user we ran into something unexpected this.dispatchEvent( new ShowToastEvent({ title: 'Barcode Scanner Error', message:'There was a problem scanning the barcode: ' + JSON.stringify(error) +' Please try aga in.', variant: 'error', mode: 'sticky' }));}).finally(() => { console.log('#finally'); // Clean up by ending capture, // whether we completed successfully or had an error this.myScanner.endCapture(); });} else { // BarcodeScanner is not available // Not running on hardware with a camera, or some other context issue console.log('Scan Barcode button should be disabled and unclickable.');console.log(event);// Let user know they need to use a mobile phone with a camerathis.dispatchEvent( new ShowToastEvent({ title: 'Barcode Scanner Is Not Available', message:'Try again from the Salesforce app on a mobile device.', variant: 'error' }));}}}

XML file:

<?xml version="1.0" encoding="UTF-8"?><LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"><apiVersion>49.0</apiVersion><isExposed>true</isExposed><masterLabel>Bar Code Scanner</masterLabel><description>This is a Bar Code Scanner Component.</description><targets><target>lightning__Tab</target></targets></LightningComponentBundle>

Now try to scan this image:

I hope you found this article helpful and interesting. Please feel for sharing your thoughts on this new feature.

--

--

SFDC Coder

Salesforce Developer / Badminton Lover / Tech Enthusiastic