onScan.js: Hardware Barcode Scanner Event Handler

raw JSON →
1.5.2 verified Thu Apr 23 auth: no javascript

onScan.js is a lightweight, framework-agnostic JavaScript library designed to accurately detect and process input from hardware barcode scanners operating in either keyboard-wedge or clipboard (paste) mode. It intelligently distinguishes between normal keyboard input and high-speed scanner input by analyzing keypress timing, prefix/suffix characters, and other configurable parameters. Upon successful detection, it triggers a custom `scan` DOM event on the attached element or invokes a specified callback function, providing the scanned code and an optional quantity. The library is currently stable at version 1.5.2 and receives updates to enhance detection algorithms and add features like `captureEvents` (v1.5) for event priority. Its primary differentiation lies in its flexibility, robust detection logic, and comprehensive options for fine-tuning scanner behavior, making it suitable for a wide range of browser-based applications that require reliable barcode input without relying on specific frameworks.

error ReferenceError: onScan is not defined
cause The `onScan` object is not available in the current scope, either because the script was not included, or it was imported incorrectly (e.g., using `require` in an ESM module without proper transpilation).
fix
If using a script tag, ensure onscan.min.js is loaded before your code. If using modules, use import onScan from 'onscan.js' for ESM or const onScan = require('onscan.js') for CommonJS.
error Barcode scanner input is visible in text fields or default browser actions occur (e.g., form submission)
cause onScan.js is not successfully intercepting and preventing the default behavior of the scanner input, or its detection parameters are not configured to block the input.
fix
Ensure captureEvents: true (v1.5+) is set in your options. Verify suffixKeyCodes matches your scanner's termination character (e.g., [13] for Enter). Consider setting preventDefault: true in options if the library's default prevention isn't working.
error The 'scan' event or `onScan` callback is not firing consistently or at all.
cause The scanner's input speed, prefix/suffix characters, or overall behavior does not match onScan.js's current detection options.
fix
Adjust options such as suffixKeyCodes, minLength, timeBeforeScanTest, and minDelayBetweenKeys. Check if reactToPaste: true is needed for clipboard-mode scanners. Use onKeyDetect callback to debug raw key codes being received.
gotcha Proper detection of barcode scanners often requires fine-tuning options like `suffixKeyCodes`, `minLength`, `timeBeforeScanTest`, and `reactToPaste` to match specific hardware behavior.
fix Consult your scanner's manual for its suffix characters (often Enter/Tab) and adjust `suffixKeyCodes`. Test `reactToPaste: true` for scanners that paste input instead of emulating keypresses.
breaking Version 1.4 introduced 'wrapped in JS module' support. While enhancing modularity, this might change how the library is accessed (e.g., via `import` or `require`) in module-aware environments, potentially breaking older direct global references if not configured correctly.
fix Update your import statements to use `import onScan from 'onscan.js'` for ESM or `const onScan = require('onscan.js')` for CommonJS. If using a global script tag, ensure no module bundler is shadowing the global `onScan` object.
gotcha New option `captureEvents` introduced in v1.5. If not set to `true`, other event listeners on the DOM element might process keydown/keypress events before onScan.js, potentially interfering with barcode detection.
fix When initializing, set `captureEvents: true` in the options object to ensure onScan.js receives and processes keyboard events with higher priority: `onScan.attachTo(document, { captureEvents: true, ... })`.
npm install onscan.js
yarn add onscan.js
pnpm add onscan.js

Initializes onScan.js on the document with common options, including a custom scan callback and a DOM event listener, then simulates a barcode scan to demonstrate functionality and output.

// Enable scan events for the entire document with custom options
onScan.attachTo(document, {
    suffixKeyCodes: [13], // enter-key expected at the end of a scan
    reactToPaste: true, // Compatibility to built-in scanners in paste-mode
    minLength: 3, // Minimum length of a scan code
    timeBeforeScanTest: 100, // Wait 100ms for more characters
    onScan: function(sCode, iQty) { // Callback for successful scan
        console.log('Scanned: ' + iQty + 'x ' + sCode); 
        document.getElementById('scanned-output').innerText = `Last Scan: ${iQty}x ${sCode}`;
    },
    onKeyDetect: function(iKeyCode){ // Output all potentially relevant key events - great for debugging!
        // console.log('Pressed: ' + iKeyCode);
    },
    captureEvents: true // new in v1.5: ensures onScan gets events first
});

// Register a traditional DOM event listener for the 'scan' event (alternative to onScan callback)
document.addEventListener('scan', function(event) {
    const sScancode = event.detail.scanCode;
    const iQuantity = event.detail.qty;
    console.log('DOM scan event: ' + iQuantity + 'x ' + sScancode);
});

// Simulate a scan programmatically - e.g. to test event handlers
// This will trigger the onScan callback and the custom DOM 'scan' event
onScan.simulate(document, 'ABC12345XYZ');

// Element to display scanned output
const outputDiv = document.createElement('div');
outputDiv.id = 'scanned-output';
outputDiv.style.marginTop = '20px';
outputDiv.style.padding = '10px';
outputDiv.style.border = '1px solid lightgray';
outputDiv.innerText = 'Waiting for scan...';
document.body.appendChild(outputDiv);