Day 14: Scan a Barcode in a Lightning Web Component (Beta) #TexeiAdventCalendar

By

2 minutes de lecture

Hello everyone, until now, we have written 13 wonderful stories. The last one is here, I hope that you enjoyed it! Today, we will talk about how we can scan a Barcode in Lightning web component (LWC) by using our mobile phone.

Now, we have the possibility to scan a QR Code or UPC Symbol by using our mobile device’s camera and mobile OS platform. When a barcode is successfully scanned, the data that was read from the barcode is returned to the Lightning web component that invoked it. And we don’t need to have a network connection.

So now, we will show you the steps to scan a BarCode in LWC, let’s go.

Firstly, you must import BarcodeScanner using the standard JavaScript import :

import { getBarcodeScanner } from 'lightning/mobileCapabilities';

after importing the BarCode Scanner API, you can now test the Availability of the API by using this function :

handleBeginScanClick(event) {
    const myScanner = getBarcodeScanner();
    if(myScanner.isAvailable()) {
// Perform scanning operations
    }
    else {
// Scanner not available
// Not running on hardware with a scanner
// Handle with message, error, beep, and so on
    }
}

So now, we have the BarCode Scanner API available. We can now begin to scan a barCode by using the function beginCapture() :

const myScanner = getBarcodeScanner();
const scanningOptions = {
    barcodeTypes: [
// Add expected barcode types here
        myScanner.barcodeTypes.QR
    ]
}
myScanner.beginCapture(scanningOptions)
    .then((result) => {
// Do something with the result of the scan
        console.log(result);
        this.scannedBarcode = result.value;
    })
    .catch((error) => {
// Handle cancellation and scanning errors here
        console.error(error);
    })
    .finally(() => {
        myScanner.endCapture();
    });

The function beginCapture() have a parametre: scanningOptions to select the type of the scan such as (QR,dataMatrix etc…), you can see all the barCodes types here .

When we scan successfully the barcode , the result is returned via a fulfilled promise. But if we have a failed result so we handle errors in the catch clause.

The last clause , is finally when we end the scan barCode. So we can call the funtion endCapture() to handle final cleanup.

barcode in Lightning web components

So now ,you can scan easily any barcode in Lightning web components, it’s amazing ;)

Hope you had a good read! Want to learn more? Check out the new article written by Mouloud HABCHI about Salesforce dynamic forms. Follow us on LinkedIn here and on Twitter here!

Read more posts