{"id":17856,"library":"onscan.js","title":"onScan.js: Hardware Barcode Scanner Event Handler","description":"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.","status":"active","version":"1.5.2","language":"javascript","source_language":"en","source_url":"https://github.com/axenox/onscan.js","tags":["javascript","barcode","RFID","scanner","scan"],"install":[{"cmd":"npm install onscan.js","lang":"bash","label":"npm"},{"cmd":"yarn add onscan.js","lang":"bash","label":"yarn"},{"cmd":"pnpm add onscan.js","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For ESM environments (Webpack, Rollup, Vite, etc.), use default import. Available since v1.4.","wrong":"const onScan = require('onscan.js');","symbol":"onScan","correct":"import onScan from 'onscan.js'"},{"note":"The primary usage pattern for direct browser inclusion, exposes `onScan` globally.","symbol":"onScan (global)","correct":"<!-- Include onscan.min.js in your HTML -->\n<script src=\"path/to/onscan.min.js\"></script>\n<script>\n  onScan.attachTo(document);\n</script>"},{"note":"For CommonJS environments (Node.js, older bundlers), use `require()`. Available since v1.4.","wrong":"import onScan from 'onscan.js';","symbol":"onScan (CommonJS)","correct":"const onScan = require('onscan.js');"}],"quickstart":{"code":"// Enable scan events for the entire document with custom options\nonScan.attachTo(document, {\n    suffixKeyCodes: [13], // enter-key expected at the end of a scan\n    reactToPaste: true, // Compatibility to built-in scanners in paste-mode\n    minLength: 3, // Minimum length of a scan code\n    timeBeforeScanTest: 100, // Wait 100ms for more characters\n    onScan: function(sCode, iQty) { // Callback for successful scan\n        console.log('Scanned: ' + iQty + 'x ' + sCode); \n        document.getElementById('scanned-output').innerText = `Last Scan: ${iQty}x ${sCode}`;\n    },\n    onKeyDetect: function(iKeyCode){ // Output all potentially relevant key events - great for debugging!\n        // console.log('Pressed: ' + iKeyCode);\n    },\n    captureEvents: true // new in v1.5: ensures onScan gets events first\n});\n\n// Register a traditional DOM event listener for the 'scan' event (alternative to onScan callback)\ndocument.addEventListener('scan', function(event) {\n    const sScancode = event.detail.scanCode;\n    const iQuantity = event.detail.qty;\n    console.log('DOM scan event: ' + iQuantity + 'x ' + sScancode);\n});\n\n// Simulate a scan programmatically - e.g. to test event handlers\n// This will trigger the onScan callback and the custom DOM 'scan' event\nonScan.simulate(document, 'ABC12345XYZ');\n\n// Element to display scanned output\nconst outputDiv = document.createElement('div');\noutputDiv.id = 'scanned-output';\noutputDiv.style.marginTop = '20px';\noutputDiv.style.padding = '10px';\noutputDiv.style.border = '1px solid lightgray';\noutputDiv.innerText = 'Waiting for scan...';\ndocument.body.appendChild(outputDiv);","lang":"javascript","description":"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."},"warnings":[{"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.","message":"Proper detection of barcode scanners often requires fine-tuning options like `suffixKeyCodes`, `minLength`, `timeBeforeScanTest`, and `reactToPaste` to match specific hardware behavior.","severity":"gotcha","affected_versions":">=1.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=1.4"},{"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, ... })`.","message":"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.","severity":"gotcha","affected_versions":"<1.5"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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.","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).","error":"ReferenceError: onScan is not defined"},{"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.","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.","error":"Barcode scanner input is visible in text fields or default browser actions occur (e.g., form submission)"},{"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.","cause":"The scanner's input speed, prefix/suffix characters, or overall behavior does not match onScan.js's current detection options.","error":"The 'scan' event or `onScan` callback is not firing consistently or at all."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}