Skip to content

Instantly share code, notes, and snippets.

@JitendraZaa
Created June 6, 2022 18:30
Show Gist options
  • Save JitendraZaa/577d1061637bdef7c9f7d70e99893166 to your computer and use it in GitHub Desktop.
Save JitendraZaa/577d1061637bdef7c9f7d70e99893166 to your computer and use it in GitHub Desktop.
Scan Barcode in LWC Natively
<template>
<div class="slds-card">
<div class="slds-box">
<lightning-button variant="brand" label="Begin Barcode Scan" title="Begin Barcode Scan"
onclick={handleBarcodeClick} class="slds-m-left_x-small">
</lightning-button>
<p class="slds-m-left_x-small">
{scannedBarcode}
</p>
</div>
</div>
</template>
/*
* @date May 2022
* @author Jitendra Zaa
* @description Demo of barcode
*/
import { LightningElement } from 'lwc';
import { getBarcodeScanner } from 'lightning/mobileCapabilities';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class Barcode_api_demo extends LightningElement {
scannedBarcode = '';
/**
* When component is initialized, detect whether to enable Scan button
*/
connectedCallback() {
this.myScanner = getBarcodeScanner();
}
/**
* Method executed on click of Barcode scan button
* @param event
*/
handleBarcodeClick(event){
if(this.myScanner.isAvailable()) {
const scanningOptions = {
barcodeTypes: [this.myScanner.barcodeTypes.QR,
this.myScanner.barcodeTypes.UPC_E,
this.myScanner.barcodeTypes.EAN_13,
this.myScanner.barcodeTypes.CODE_39 ],
instructionText: 'Scan a QR , UPC , EAN 13, Code 39',
successText: 'Scanning complete.'
};
this.myScanner.beginCapture(scanningOptions)
.then((result) => {
this.scannedBarcode = result.value;
})
.catch((error) => {
this.showError('error',error);
})
.finally(() => {
this.myScanner.endCapture();
});
}
else {
this.showError('Error','Scanner not supported on this device');
}
}
/**
* Utility method to show error message
* @param title
* @param msg
*/
showError(title,msg) {
const event = new ShowToastEvent({
title: title,
message: msg,
error : 'error'
});
this.dispatchEvent(event);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment