Salesforce LWC: Barcode Scanner

For scanning barcode in Salesforce, Salesforce is releasing Barcode API as part of Winter 21 release. Currently it is in beta with few limitation which we will see at the end of this blog.
To implement Barcode scanning functionality you need to just import barcode API in your LWC which is :


import { getBarcodeScanner } from 'lightning/mobileCapabilities';

Now barcode scanner functionality will only work on devices which has camera feature so to check that we need to check first whether Scanning feature is available in current device or not. To check this you need to use above API. As part of this API there is a method isAvailable(), this method will help to determine whether current device support scanning feature or not.
So every time when our LWC component will load then in connectedCallback() method we can check this:

1
2
3
4
5
6
connectedCallback() {
        this.myScanner = getBarcodeScanner();
        if (this.myScanner == null || !this.myScanner.isAvailable()) {
            this.scanButtonDisabled = true;
        }
    }

Now after checking scanning feature in our device it is time to write logic for scanning feature. To scan the barcode we just need to call one method which is also part of this scanning API: beginCapture().
So once you will click on button for barcode scanning then we will call this method in our onclick event handler method which will enable the Camera and capture the QR code. After capturing the QR code you can read the result using decodeURIComponent() method.

decodeURIComponent() method is javaScript standard method which is use to decode the Uniform Resource Identifier (URI).

Example:

1. HTML Code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<template>
    <div style="background-color:white">
        <lightning-card  variant="Narrow"  title="Barcode Scanner" icon-name="standard:pricebook">
            <div class="slds-p-horizontal_small">
                <div class="slds-text-align_center">
                    <lightning-button
                        variant="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>
                <div class="slds-var-m-vertical_large slds-var-p-vertical_medium slds-text-align_center slds-border_top slds-border_bottom">
                    Scanned barcode value is:
                    <span class="slds-text-heading_small">{scannedBarcode}</span>
                </div>
            </div>
        </lightning-card>
    </div>
</template>

2. JavaScript Logic:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getBarcodeScanner } from 'lightning/mobileCapabilities';

export default class BarCodeScannerCmp extends LightningElement {
    myScanner;
    scanButtonDisabled = false;
    scannedBarcode = '';
    connectedCallback() {
        this.myScanner = getBarcodeScanner();
        if (this.myScanner == null || !this.myScanner.isAvailable()) {
            this.scanButtonDisabled = true;
        }
    }

    handleBeginScanClick(event) {
        this.scannedBarcode = '';
        if (this.myScanner != null && this.myScanner.isAvailable()) {
            const scanningOptions = {
                barcodeTypes: [this.myScanner.barcodeTypes.QR]
            };
            this.myScanner.beginCapture(scanningOptions).then((result) => {
                    this.scannedBarcode = decodeURIComponent(result.value);
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Successful Scan',
                            message: 'Barcode scanned successfully.',
                            variant: 'success'
                        })
                    );
                }).catch((error) => {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Barcode Scanner Error',
                            message:
                                'There was a problem scanning the barcode: ' +
                                JSON.stringify(error) +
                                ' Please try again.',
                            variant: 'error',
                            mode: 'sticky'
                        })
                    );
                }).finally(() => {
                    this.myScanner.endCapture();
                });
        }else{
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Barcode Scanner Is Not Available',
                    message:
                        'Try again from the Salesforce app on a mobile device.',
                    variant: 'error'
                })
            );
        }
    }
}

Code Reference:

https://github.com/flighttoSalesforce/barcodeScanner

Limitations:

1. BarcodeScanner requires the use of the mobile device camera. You must grant access to your app to access your mobile camera.
2. The quality of camera affects Barcode recognition.
3. Not all type of barcode can be scanned using this API.

References:

1. Salesforce Lightning Component Library
2.  Developer Mozilla

Other Useful blogs:

1. https://www.sfprompt.com
2. https://manish-porwal.blogspot.com


Comments

Followers

Popular posts from this blog

Salesforce LWC: Multi-Record Creation using Lightning Web Component

Salesforce LWC: Basic Drag and Drop Functionality

Salesforce Lightning Web Component: Dynamic Column Selection in Lightning Datatable