Forked from neelbhanushali/usb-connected-hand-held-barcode-scanner-input.js
Created
September 20, 2023 02:44
-
-
Save marcossaore/f9e6c3d22ad4c23f574ad8fb6eb4415c to your computer and use it in GitHub Desktop.
Javascript for detecting usb connected - hand held - barcode scanner input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Author: Neel Bhanushali <[email protected]> | |
document.addEventListener('keydown', function(e) { | |
// add scan property to window if it does not exist | |
if(!window.hasOwnProperty('scan')) { | |
window.scan = [] | |
} | |
// if key stroke appears after 10 ms, empty scan array | |
if(window.scan.length > 0 && (e.timeStamp - window.scan.slice(-1)[0].timeStamp) > 10) { | |
window.scan = [] | |
} | |
// if key store is enter and scan array contains keystrokes | |
// dispatch `scanComplete` with keystrokes in detail property | |
// empty scan array after dispatching event | |
if(e.key === "Enter" && window.scan.length > 0) { | |
let scannedString = window.scan.reduce(function(scannedString, entry) { | |
return scannedString + entry.key | |
}, "") | |
window.scan = [] | |
return document.dispatchEvent(new CustomEvent('scanComplete', {detail: scannedString})) | |
} | |
// do not listen to shift event, since key for next keystroke already contains a capital letter | |
// or to be specific the letter that appears when that key is pressed with shift key | |
if(e.key !== "Shift") { | |
// push `key`, `timeStamp` and calculated `timeStampDiff` to scan array | |
let data = JSON.parse(JSON.stringify(e, ['key', 'timeStamp'])) | |
data.timeStampDiff = window.scan.length > 0 ? data.timeStamp - window.scan.slice(-1)[0].timeStamp : 0; | |
window.scan.push(data) | |
} | |
}) | |
// listen to `scanComplete` event on document | |
document.addEventListener('scanComplete', function(e) { console.log(e.detail) }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment