Skip to main content

Barcode Scanner 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 Barcode Scanner API which now supports Scanning barcodes from a Lightning web component for mobile devices.

salesforceScanner.html :-

<!-- barcodeScannerExample.html -->
<template>
    <div class="slds-text-align_center">
        <span class="slds-text-heading_large">
<lightning-icon icon-name="utility:scan" alternative-text="XML file" title="XML">
</lightning-icon>Salesforce Wallah</span>
    </div>
    <template if:true={scannedBarcode}>
        <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>
    </template>
    <div class="slds-align_absolute-center slds-m-vertical_large">
        <lightning-button
            variant="brand"
            class="slds-var-m-left_x-small"
            disabled={scanButtonDisabled}
            icon-name="utility:scan"
            label="Scan Barcode"
            title="Open a camera view and look for a barcode to scan"
            onclick={handleBeginScanClick}>
        </lightning-button>
    </div>
</template>


salesforceScanner.js :-

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getBarcodeScanner } from 'lightning/mobileCapabilities';

export default class SalesforceScanner 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],
                instructionText: 'Scan a QR Code',
                successText: 'Scanning complete.'
            };
            this.myScanner
                .beginCapture(scanningOptions)
                .then((result) => {
                    this.scannedBarcode = result.value;
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Successful Scan',
                            message: 'Barcode scanned successfully.',
                            variant: 'success'
                        })
                    );
                })
                .catch((error) => {
                    // Handle cancellation and unexpected errors here
                    console.error(error);

                    if (error.code == 'userDismissedScanner') {
                        // User clicked Cancel
                        this.dispatchEvent(
                            new ShowToastEvent({
                                title: 'Scanning Cancelled',
                                message:
                                    'You cancelled the scanning session.',
                                mode: 'sticky'
                            })
                        );
                    }
                    else {
                        // Inform the user we ran into something unexpected
                        this.dispatchEvent(
                            new ShowToastEvent({
                                title: 'Barcode Scanner Error',
                                message:
                                    'There was a problem scanning the barcode: ' +
                                    error.message,
                                variant: 'error',
                                mode: 'sticky'
                            })
                        );
                    }
                })
                .finally(() => {
                    this.myScanner.endCapture();
                });
        } else {
            alert(
                'Scan Barcode button should be disabled and unclickable.'
            );
            console.log('Somehow it got clicked: ');
            console.log(event);

            // Let user know they need to use a mobile phone with a camera
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Barcode Scanner Is Not Available',
                    message:
                        'Try again from the Salesforce app on a mobile device.',
                    variant: 'error'
                })
            );
        }
    }
}


salesforceScanner.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__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Default</target>
        <target>lightningCommunity__Page</target>
      </targets>
</LightningComponentBundle>


Resources :-

Note :-

This Code only work on Mobile salesforce, on desktop it will not work.




Comments

Popular Posts

Top 100 Most common used Apex Method in Salesforce

  Here are 100 more Apex methods in Salesforce: 1.       insert: Inserts records into the database. 2.       update: Updates records in the database. 3.       delete: Deletes records from the database. 4.       upsert: Updates or inserts records into the database. 5.       query: Retrieves records from the database using SOQL. 6.       getContent: Retrieves the content of a document or attachment. 7.       getContentAsPDF: Generates a PDF file from a Visualforce page or HTML content. 8.       addError: Adds a custom error message to a record and prevents saving. 9.       start: Initiates processing in batch Apex. 10.    execute: Processes a batch of records in batch Apex. 11.    finish: Finalizes processing in batch Apex....

How to create ICS/Calendar File | Helps you to download the calendar invites

  Want to know how to create ICS(Internet Calendar Scheduling) file for Business purpose....đź‘€    ICS (Internet Calendar Scheduling) file is a calendar file saved in a universal calendar format used by several email and calendar programs, including Microsoft Outlook, Google Calendar, Notes and Apple Calendar. It enables users to publish and share calendar information on the web and over email. Lets see the code. The code is written in lwc(Lightning web component). HTML:   <template> <div class="login-container"> <h1 style="size: 14px;"><b>Create ICS File</b></h1> <div class="form-group"> <lightning-input type="datetime" name="input1" value={EventEndValue} onchange={startDate} label="Enter Start date/time value" ></lightning-input> </div> <div class="form-group"> <lightning-input type="...

Salesforce Flow Updates – Spring’25 Release

  In this blog, we’ll dive into the Salesforce Flow Updates introduced in the Spring ’25 Release. We’ll explore their practical applications and how they enhance user experiences. This release emphasizes improved usability, efficiency, and functionality in Salesforce Flows. With upgrades like enhanced Flow Builder features, reactive screen actions, and progress indicators, Spring ’25 takes automation to the next level. Let’s explore each Salesforce Flow Updates 1. View Flow Versions Side by Side The Spring ’25 update introduces the ability to open flow versions in separate tabs directly within the Flow Builder. This feature allows you to compare different versions side by side on the same canvas, streamlining the debugging process and improving efficiency. 2.Smarter Search in Resource Picker The resource picker now features enhanced nested search functionality, simplifying the process of finding the right resources. Whether you're looking for record variables, custom labels, or glo...

Sharing records by Apex in Salesforce

  Greetings, everyone! In today's session, we'll delve into the topic of sharing records within an Apex class. As we're aware, there exist various methods through which we can accomplish the sharing of records. We engage in record sharing primarily when the object's Organization Wide Default (OWD) settings are set to private. Sharing settings come into play when certain predefined criteria are met, allowing us to extend access to records to designated groups or roles. In cases where intricate logic is involved, manual sharing is employed. While this approach proves beneficial for specific records, instances where a multitude of records require automated handling, Apex sharing becomes the preferred solution. Salesforce offers a 'Share' object for each type of object, with distinct naming conventions: For standard objects, it's 'StandardobjectName+Share', such as 'AccountShare' for the 'Account' object. Custom objects follow the pattern...

Capture Real time data using CDC(Change Data Capture) in Salesforce | SF Fact #05

Change Data Capture (CDC) enables receiving near-real-time updates for Salesforce records and synchronizing them with an external data store. CDC publishes change events that reflect modifications to Salesforce records, including new records, updates, deletions, and undeletions. These events can be subscribed to in a Lightning Web Component (LWC) using the Emp API. To meet the business requirement of creating a task whenever a user manually changes an opportunity's status to "Closed Won," use CDC events and a generic LWC on the opportunity record page. This solution avoids the need for Apex triggers or record-triggered flows. How to enable CDC? Go to setup Search Change Data Capture Add Entities The  lightning/empApi  module provides access to methods for subscribing to a streaming channel and listening to event messages. All streaming channels are supported, including channels for platform events, PushTopic events, generic events, and Change Data Capture events. This co...