Integrate Barcode Reader Using JavaScript
Integration of barcode reader device with your application using JavaScript
I came across this scenario a few weeks ago when I had to do integration of a barcode scanner device with my application. The purpose of doing it is simple, the person handling the store counter should be able to scan the products and the same product will get reflected on the shopping list.
I have mostly worked on the software development and had the least interaction with the hardware devices. I found this challenging initially, but got some help online and successfully integrated the device. I thought of sharing the same thing with you all.
Barcode scanner devices are similar to keyboard devices. It means it will capture the barcode in the same way we type on the keypad. We just need to get that event and we will be able to read the barcode.
Most of the barcode scanners/readers have enter event already configured. That means whenever we scan any barcode, after scanning is completed, it will automatically hit enter event. This is very important in order to get that the device has completed reading the barcode and we can move to the next step.
We can check this easily by following the below steps.
- Begin by opening an Excel/Notepad file.
- Scan any barcode and see if the cursor moves to the second line after writing/copying barcode into the file.
If device is not operating the way we expected above, we need to explicitly add the enter event to device. It can be easily done by scanning the barcode for enter event. This barcode will be generally provided in the user manual sent with scanner device. If not shared in user manual, we can easily get it over internet.
Get Vinayak kharate’s stories in your inbox
Join Medium for free to get updates from this writer.
Now, once we are sure that enter event is configured, we can move to the coding part using JavaScript.
On mounting of the component, we can call the function which will have keydown event listener.
function initiateScanner() {
let barcode = "";
let interval; document.addEventListener("keydown", (e) => {
if (interval) {
clearInterval(interval);
} if (e.code === "Enter") {
if ( barcode ) {
getBarcode(barcode);
}
barcode = "";
return;
} if (e.key !== "Shift") {
barcode += e.key;
} interval = setInterval(() => (barcode = ""), 200); });
}const getBarcode= (barcode) => {
console.log("barcode num", barcode);
};
Here, initiateScanner should be triggered once component is mounted. Then if user scan the product, keydown event will be triggered and we will keep on adding the keydown input until we get the enter key event.
Once enter key event is received, we will call another function getBarcode.
That’s it for this article. If you find this article helpful, please do not forgot to check my other articles too!




