How to Use Barcode Scanner API In LWC?

How to Use Barcode API In LWC?
In this blog, you will learn how you can use the newly launched Barcode Scanner API for lightning web component in salesforce.

Salesforce released a new BarcodeScanner API which now supports Scanning barcodes from a Lightning web component for mobile devices.


myBarcodeScanner.html

<template>
    <lightning-card icon-name="utility:scan" title="Barcode Scanner">
        <div class="slds-var-p-horizontal_medium">
            <lightning-button variant="netural" label="Click Here to Scan" title="Click Here to Scan" 
            onclick={handleClick}></lightning-button>
            <div class="slds-var-p-vertical_large">
                <span>{scannedResult}</span>
            </div>
        </div>
    </lightning-card>
</template>


myBarcodeScanner.js 

import { LightningElement } from 'lwc';
import { getBarcodeScanner } from 'lightning/mobileCapabilities'; //import barcode API

export default class MyBarcodeScanner extends LightningElement {

    scannedResult ='';

    connectedCallback(){
        this.loadScanner = getBarcodeScanner(); 
    }

    handleClick(event){

        const loadScanner = getBarcodeScanner();

        if(loadScanner.isAvailable()){ //check if device has mobile capabilities
            const scanOptions ={
                barcodeTypes:[this.loadScanner.barcodeTypes.QR], // barcode types 
                instructionText :'Scan a QR Code',
                successText :'Scan Completed..!'
            };

            loadScanner.beginCapture(scanOptions)
            .then((result)=>{
                this.scannedResult = result.value;   // print final result on the screen 
            })
            .catch((error)=>{
                this.showError('error',error);
            })
            .finally(()=>{
                loadScanner.endCapture();
            })
        }
        else{
            this.showError('Error','Device Not Supported..!');
        }
    }
}


myBarcodeScanner.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>


Resources

Demo


Follow Us

Posted By : Sudeer Kamat Date :

view_module Related

Comments 0