Last active
October 20, 2022 02:37
-
-
Save jhargis/d39ac7dc32279b665914ff89dd5623d2 to your computer and use it in GitHub Desktop.
javascript barcode scanner
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
document.addEventListener('DOMContentLoaded', function () { | |
if(!window.hasOwnProperty('scan_data')) { | |
window.scan_data = []; | |
window.scan_prefix_target = null; | |
} | |
// keystroke speed < 80ms & min total length of 4 chars | |
const scan_min_chars = 4, scan_keystroke_window_ms = 80; | |
let _scan_timer = window.setTimeout(function() { window.scan_data = []; }, 0); | |
const scan_meta_keys = ['Control', 'Alt', 'Meta', 'Tab', 'Escape', 'Shift']; | |
document.addEventListener('keydown', function(e) { | |
if(scan_meta_keys.indexOf(e.key) !== -1){ return; } | |
window.clearTimeout(_scan_timer); | |
if(e.key === "Enter" && window.scan_data.length > scan_min_chars) { | |
let scannedStr = window.scan_data.join(""); | |
window.scan_data = []; | |
return document.dispatchEvent(new CustomEvent('scanComplete', {detail: scannedStr})) | |
} else { | |
window.scan_data.push(e.key); | |
_scan_timer = window.setTimeout(function() { window.scan_data = []; }, scan_keystroke_window_ms); | |
} | |
}); | |
// scanner data received. dispatch | |
document.addEventListener('scanComplete', function(e) { | |
console.log(e.detail); | |
let d = e.detail; | |
if (d.startsWith('prefix1')) { | |
if (!window.scan_prefix_target) { | |
console.log('You must define a prefix target first.'); | |
return; | |
} else { | |
console.log('redirect to prefix1 + prefix target id'); | |
} | |
} | |
if (d.startsWith('prefix2')) { | |
console.log('setting prefix target: prefix2'); | |
window.scan_ws_target = 'prefix2'; | |
// do something else.... | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment