Skip to content

Barcode Scanner Emulator

How to Test Barcode Scanners in Web Applications

Many USB and Bluetooth barcode scanners send decoded data as keyboard input, so a focused field in a web application can receive a scan without a scanner-specific browser API. Serial ports and vendor SDKs are separate integrations. You can test the keyboard path with a physical scanner or with simulated keystrokes.

A web application usually sees a barcode scanner as a keyboard. The test is whether the focused control receives the payload your application expects, and whether the page handles the terminator the scanner is configured to send. That terminator may be Enter, Tab, or nothing.

Use a Barcode Input Tester session when a physical scanner is attached. Use the Barcode Scanner Emulator when you need the same keyboard path during development and the hardware is not on the desk. A broader pass over focus, layout, and POS workflows is in How to Test Barcode Scanner Input. This guide stays on the browser application: capture, suffixes, validation, and the events you can actually observe.

How Barcode Scanners Communicate With Web Applications

The interface mode decides what the page can receive. Confirm it before changing form code. A scanner can often switch modes by scanning a configuration barcode from the manufacturer's manual.

USB HID keyboard wedge

In USB HID keyboard mode the scanner enumerates as a keyboard. The operating system loads its normal keyboard driver. After the scanner decodes a symbol, it sends the characters as keystrokes to whichever control has keyboard focus. The page listens for those keystrokes, or reads the text they insert. It does not open a connection to the device.

That path is why a checkout field, a search box, or any other text input can accept a scan with ordinary HTML. The HID keyboard wedge guide covers the keystroke sequence, prefixes, and suffixes in more detail.

Bluetooth HID

A Bluetooth scanner paired as a keyboard uses the same application path. The host treats it as a HID keyboard, and the focused field receives keystrokes. Pairing, battery, and the radio are device concerns. Once the characters reach the browser, the page handles them the same way it handles USB wedge input.

Serial and virtual COM port

A serial scanner, including many USB virtual COM port modes, sends the decoded text as bytes on a port. Focus does not choose the destination. The process that opens the port does. A text field that only listens for keystrokes will not see that stream.

Chromium-based browsers can open a serial port through the Web Serial API after the user selects the port and grants permission. Firefox and Safari do not provide that API. A wedge test does not exercise a serial integration, and a serial test does not tell you what a wedge scanner will type.

Vendor-specific interfaces

Some devices use a vendor SDK, OPOS, JPOS, or a non-keyboard HID interface such as USB HID POS. Those interfaces do not type into the focused field. A normal web page cannot load a native SDK. Chromium can request some non-keyboard HID devices through WebHID after a user gesture. Keyboard-class HID devices stay blocked, so a wedge scanner remains indistinguishable from a keyboard. Treat a vendor interface as its own integration and test it with the software that actually opens that interface.

What the browser can see

A wedge scan arrives as keydown and keyup events, and printable characters update the focused field. The browser does not receive a device name, a USB serial number, or a flag that says "scanner." Browsers that implement WebHID still refuse keyboard interfaces, so page script cannot read the raw HID reports of a wedge scanner either.

event.key is the character or key name after the operating system applies the active keyboard layout. event.code names the physical key, such as Digit1 or Numpad1, and can stay the same when a layout mismatch changes event.key. Neither property identifies the hardware.

How to Test a Physical Barcode Scanner in a Browser

Run this before debugging application code. It shows the exact string and terminator the browser received.

  1. Connect the scanner and wait until it shows it has power. For Bluetooth, finish pairing and confirm the host is using a keyboard profile.
  2. Confirm the input mode. Keyboard wedge, USB HID keyboard, or Bluetooth HID keyboard can type into a field. Serial, SPP, and vendor-SDK modes will not.
  3. Open the Barcode Input Tester.
  4. Click Start Test, or click the scan area. It turns blue when it is ready. The page does not take focus on its own.
  5. Scan a barcode whose payload you already know. Start with a short numeric value, then scan a value that includes the punctuation your application stores.
  6. Read the captured value and the character count. Compare both with the payload you expect, including any prefix the scanner inserts before the data.
  7. Check the suffix. The tester reports ENTER, TAB, or None. With Auto capture on, the result appears after Enter, Tab, or a short pause once the keys stop. Turn Auto capture off when you want the capture held until you press Stop.
  8. Compare that result with the string your application should store. A prefix, a substituted character, or a missing terminator should be fixed in the scanner configuration or handled deliberately in the page. Do not treat it as a decode failure until this comparison is done.

The tester records keyboard events the browser can see. It cannot identify the USB device or read a serial port. When a text editor receives the scan and the browser does not, continue with Scanner Works in Notepad but Not POS.

Capture Barcode Scanner Input With JavaScript

A scanner types into the element that has focus. Give the field a visible label, leave it as a normal text input so keyboard users can type a code, and read the value when the workflow says the entry is complete. The page below does that. Enter submits the form once. Tab completes a non-empty value and then lets the browser move focus. A scan with no terminator stays in the field until someone activates Look up.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Barcode input example</title>
</head>
<body>
  <form id="barcode-form">
    <label for="barcode">Barcode</label>
    <input id="barcode" name="barcode" type="text" autocomplete="off" spellcheck="false">
    <button type="submit">Look up</button>
  </form>
  <p id="message" role="status"></p>
  <ul id="accepted"></ul>
  <script>
    const form = document.querySelector('#barcode-form')
    const field = document.querySelector('#barcode')
    const message = document.querySelector('#message')
    const list = document.querySelector('#accepted')

    if (
      !(form instanceof HTMLFormElement) ||
      !(field instanceof HTMLInputElement) ||
      !(message instanceof HTMLElement) ||
      !(list instanceof HTMLUListElement)
    ) {
      throw new Error('Barcode form markup is missing.')
    }

    function payload(raw) {
      return raw.replace(/[\r\n]/g, '').trim()
    }

    function classify(raw) {
      const value = payload(raw)
      if (!value) {
        return { status: 'empty' }
      }
      if (/[\u0000-\u001F\u007F]/.test(value)) {
        return {
          status: 'invalid',
          message: 'Control character in the barcode. Check the prefix, suffix, and symbology identifier.',
        }
      }
      return { status: 'ok', value }
    }

    function accept(value) {
      const item = document.createElement('li')
      item.textContent = value
      list.append(item)
      message.textContent = 'Accepted ' + value
      field.value = ''
    }

    function reject(text) {
      message.textContent = text
    }

    form.addEventListener('submit', (event) => {
      event.preventDefault()
      const outcome = classify(field.value)
      if (outcome.status === 'empty') {
        reject('No barcode received.')
        field.focus()
        return
      }
      if (outcome.status === 'invalid') {
        reject(outcome.message)
        field.focus()
        return
      }
      accept(outcome.value)
      field.focus()
    })

    field.addEventListener('keydown', (event) => {
      if (event.key !== 'Tab' || event.shiftKey) {
        return
      }
      const outcome = classify(field.value)
      if (outcome.status === 'empty') {
        return
      }
      if (outcome.status === 'invalid') {
        event.preventDefault()
        reject(outcome.message)
        return
      }
      accept(outcome.value)
    })

    field.focus()
  </script>
</body>
</html>

Save that file and open it in a desktop browser. Click the field if focus has moved. A wedge scanner, or the emulator in the next section, then types into #barcode.

Focus is required. If document.activeElement is the document body, a button, or a different input, this field's listeners do not see the scan. The characters land in the focused control, or they are lost. Call field.focus() when the workflow is ready for a scan, including after a dialog closes.

Empty input is ignored. The form stays in place, and the status text says that nothing was received. Whitespace alone is empty after trim().

The example does not add Enter or Tab. If the scanner is not configured to send them, the value remains in the field and Look up is the completion path. autocomplete="off" reduces the chance that a saved value replaces the scan. The label, the button, and Shift+Tab stay available, so a person can enter a code without a scanner.

Handle Enter in one place. This example uses the form submit event, which also covers the Look up button and a keyboard Enter. A second keydown listener for Enter would record the same scan twice. If the input is not inside a form, listen for Enter on keydown and call preventDefault() so an ancestor form does not submit as well:

field.addEventListener('keydown', (event) => {
  if (event.key !== 'Enter') {
    return
  }

  event.preventDefault()
  const value = field.value.trim()
  if (!value) {
    return
  }

  console.log(value)
  field.value = ''
})

Clear the field after a successful accept so the next scan does not append to the previous payload. After Enter, the example focuses the same field again because that workflow expects another scan in the same box. After Tab, it leaves focus alone so the browser can move to the next control.

Handling ENTER and TAB Suffixes

A suffix is a key the scanner may send after the payload. It is a device setting. Enter is common, and it is optional. The ENTER vs TAB suffixes guide describes how to tell the terminators apart. Confirm the setting on the scanner you are testing, then make the page match that workflow.

ENTER

Enter inside a one-line text field submits the enclosing form in current browsers. Use that when one scan should commit the value, as in a lookup box. preventDefault() on the submit event stops the browser from navigating away. Omit it when a full page navigation is the behavior you want.

If the barcode appears and the form does nothing, the scanner may be sending no suffix. Barcode Scanner Missing ENTER walks through that configuration. Some devices send NumPad Enter. event.key is still "Enter". Check event.key, not only event.code === "Enter", or that scanner will look broken.

TAB

Tab moves focus to the next focusable control. That suits a sequence such as product code, then quantity. It surprises a form that expected Enter to submit.

Read the value in keydown while the field still has focus. The browser moves focus after that event. Leave the default action in place when the next control should receive focus. preventDefault() keeps focus where it is, which is useful when the value is invalid and you want the operator to see it. Ignore Shift+Tab so a keyboard user can move backward through the form. A scanner Tab suffix is Tab without Shift.

A Tab suffix can also move focus before your code reads the field, if the listener is on blur or change and something else clears the control. Read the value from the keydown event's target.

No suffix

With no suffix, the payload sits in the field. The application has to decide when the scan is finished. An explicit button, a later Enter from the operator, or moving to another step are reliable completion points. An inactivity timer can treat a pause in typing as the end of a scan. That timer is a heuristic. A slow scanner, a Bluetooth delay, or a person who types quickly can land on the wrong side of the threshold. Prefer a configured suffix when the workflow needs a hard end-of-scan signal.

Configuration differences

Scanners from the same brand can ship with different suffixes, and a configuration barcode can change the suffix without any change in your JavaScript. Some devices send a prefix, a symbology identifier such as ]C1, or CR and LF. Test the three terminator settings your users can actually select: Enter, Tab, and none. Record which one the deployed scanners use, and test the page against that setting.

Barcode Scanner Input Validation

Validate the string the field received. Do not assume every barcode has the same length, character set, or checksum. Code 128 and QR payloads vary. EAN-13 is 13 digits. An application that stores both needs rules for both.

Empty input. Reject or ignore it. A suffix with no payload, or a Look up click on a blank field, should not create a record.

Unexpected characters. Compare the received string with a known label. A layout mismatch often shows up as a changed symbol, such as a shifted digit or punctuation, while the length stays the same. Control characters can come from a prefix or from a GS1 group separator. Allow the characters your format defines. The example above rejects ASCII control characters so they stay visible in the status text. A GS1 parser that expects a group separator should allow that character and reject the rest.

Length. Enforce the lengths your application accepts. A global minimum and maximum is safer than one required length when the form receives more than one symbology. maxlength on the input will silently truncate a longer payload, so set it only when every accepted code fits.

Prefix. Strip a prefix only when you configured the scanner to send that exact prefix and the application does not store it.

function withoutConfiguredPrefix(value, prefix) {
  if (prefix && value.startsWith(prefix)) {
    return value.slice(prefix.length)
  }
  return value
}

An AIM symbology identifier is data if the scanner is set to transmit it. Leave it in place until you have decided whether the application stores it.

Suffix. Keep the terminator out of the stored value. Enter and Tab are keys. They are not inserted into a normal text input. A serial payload may still include CR or LF bytes. Strip those at the boundary where you parse the serial stream, and test that you do not strip them from the middle of a payload that legitimately contains them.

Duplicate submissions. One scan can be handled twice if both keydown and submit run for the same Enter. Use a single completion path. A second scan of the same code is a different question. A warehouse form may increment quantity. A ticket form may reject a code that was already redeemed. Put that rule in the application, and test it on purpose. The browser cannot tell a second trigger pull from a second listener.

Application rules. Checksums belong to specific symbologies. EAN-13 uses the last digit as a check digit. This function accepts only that format:

function isEan13(value) {
  if (!/^\d{13}$/.test(value)) {
    return false
  }

  let sum = 0
  for (let index = 0; index < 12; index += 1) {
    const digit = Number(value[index])
    sum += index % 2 === 0 ? digit : digit * 3
  }

  const check = (10 - (sum % 10)) % 10
  return check === Number(value[12])
}

Code 128, Code 39, and QR do not use that calculation. The scanner may already have checked its own symbology and transmitted the human-readable data. Validate the formats you store, and repeat the check on the server. The posted string is ordinary user input. The browser cannot prove that a scanner produced it.

Testing Barcode Scanner Input Without Physical Hardware

The Barcode Scanner Emulator is a desktop app for Windows, macOS, and Linux. You enter the text to send, choose a typing delay, and choose a suffix of none, ENTER, or TAB. A global shortcut types that text into the focused application. It reproduces the keyboard path a wedge scanner uses. It does not illuminate a label, read a symbol, or decode a symbology.

Use the example page above, or the page you are building:

  1. Open the page in a desktop browser and click the barcode field.
  2. In the emulator, enter a known value such as 123456789012.
  3. Set the suffix to ENTER. Set the typing delay if you want the burst to resemble a scanner you already measured.
  4. Press the emulator's global scan shortcut while the browser field still has focus.
  5. Confirm the status text and that the value was accepted once.
  6. Repeat with TAB. Focus should move, and the value should be accepted once.
  7. Repeat with no suffix. The text should remain in the field until you activate Look up.
  8. Focus the Barcode Input Tester and send the same value again. Compare the captured string, prefix, and suffix with what the application stored.

Installation and the first shortcut are covered in Getting Started. After a settings change, send one scan into the input tester before you trust the result in the application.

Hardware is still required for the optical and device-specific parts of the test:

  • Whether that scanner can decode the printed or displayed symbol, including damaged labels, size, contrast, and distance.
  • Symbology support. A 1D laser scanner cannot read a QR code. See QR Code Testing.
  • USB enumeration, Bluetooth pairing, and the scanner's own keyboard-layout and suffix configuration.
  • Serial, HID POS, and vendor SDK integrations.

The emulator is the right tool for application logic along the keyboard path. It is the wrong tool for proving that a particular scanner reads a particular label.

Debugging Barcode Scanner Keyboard Events

Watch the events in this order when the stored value is wrong.

keydown. Fires for every key, including Enter and Tab, before the browser inserts a character or moves focus. Read the terminator here. event.repeat is true when a key is held down. A wedge scanner normally sends a distinct press for each character.

input. Fires on the field after a printable character changes its value. It is the right event to watch if you need the text as it grows. It does not fire for Enter or Tab, because those keys do not insert a character into a text input.

change. Fires after the value commits, typically when the field loses focus. A scanner that leaves focus in the same field will not produce change at the end of the scan. Do not use change as the only completion signal.

event.key and event.code. Log both when a character is wrong. A mismatch between the scanner layout and the operating-system layout changes event.key and leaves event.code looking like the key the scanner intended. Digits from the numeric keypad use Numpad1 and similar codes. Some input masks treat those differently from Digit1. Barcode Scanner Wrong Keyboard Layout explains the layout mismatch.

Focus. Log document.activeElement immediately before a scan. If it is not the barcode field, the rest of the trace is explaining the wrong control. Iframes have their own focus. A scan into an embedded frame is visible to script inside that frame.

Timing. Scanners often finish a short payload in well under a second. The input tester compares the average gap between characters with a 100 ms threshold and labels the result as timing, not as a hardware identification. A gap threshold can treat a fast typist, autofill, or the emulator as a scanner. A scanner with an inter-character delay, a Bluetooth link, or a long payload can look like typing. Use the captured value and the suffix. Use timing as a clue.

The Keyboard Event Tester lists each keydown and keyup with key, code, modifiers, and timestamps. Use it when the assembled string hides a prefix key or a numpad code. The log is browser events. It is not raw USB traffic.

Common Problems in Web Applications

The scan goes to the wrong field. Wedge input follows focus. Click the target field after every navigation, dialog, or validation message that moves focus. A modal without a text field can swallow the scan as shortcut keys.

The scanner works in a text editor and not in the browser. The device is typing. The page is not accepting those keys. Check focus, a disabled or read-only input, and a keydown listener that calls preventDefault() on printable keys. A listener that only handles paste never sees wedge input. Start with Barcode Scanner Not Working if no application receives characters.

Enter submits the form twice or navigates away. The browser submits the form, and your listener also handles Enter. Call preventDefault() on one of those paths and process the value once. A multi-field form can submit before later fields are filled when the scanner sends Enter. Use Tab for that workflow, or prevent the submit until the form is complete.

Tab changes focus. That is the Tab key. Either configure Enter on the scanner, or read the value in keydown and allow the focus move. See the suffix section above.

The keyboard layout is wrong. Digits may survive a mismatch that changes punctuation. Scan a known value that contains the symbols you store, on the layout the workstation actually uses.

The same scan creates two records. Look for two listeners on one Enter before you look for two physical scans. Then test a deliberate second scan and confirm the quantity or duplicate rule your application documents.

The value is missing or truncated. A maxlength attribute, an input mask, or preventDefault() on character keys can drop or cut the payload. Compare the character count in the input tester with the value in your field. A prefix can also make a correct payload look too long.

QR codes never appear. The scanner may be 1D-only, or the QR symbology may be disabled. The application cannot fix that. Confirm the hardware with QR Code Testing, then return to the field test.

Web Application Testing Checklist

Use this on the build you intend to ship, in each browser you support. Check a fresh profile as well as a profile with password-manager and autofill extensions, because those extensions move focus.

  • The scanner is connected or paired, and the host shows it ready.
  • The scanner is in keyboard-wedge mode, not serial or a vendor SDK mode.
  • The barcode field is focused immediately before the scan. document.activeElement is that field.
  • A known barcode arrives character for character, including length.
  • An ENTER suffix submits or accepts the value once and does not leave the terminator in the stored string.
  • A TAB suffix moves focus to the control you intend, and the value is read before the move.
  • A no-suffix configuration leaves the value available until the application completes it.
  • An empty submission is rejected or ignored.
  • One scan does not create two records. A second real scan follows the application's duplicate rule.
  • Punctuation, symbols, and any GS1 separator your formats use survive the round trip.
  • The scanner keyboard layout and the operating-system layout produce the characters printed on the label.
  • After unplugging and reconnecting, or after the Bluetooth link drops, the next scan still reaches the field.
  • Several scans in a row remain separate values. The field does not concatenate them.
  • The same checks pass in the browsers you support, with and without common autofill extensions.

For dialogs, tab order across a whole checkout, and POS quantity flows, continue with the barcode scanner testing guide.

Test Case Matrix

The scanner column is what the device and the browser do. The expected behavior column is what the application should do in response. Business rules, such as whether a repeated product code increments quantity, belong to the application. State them in the test instead of assuming one rule for every product.

Scenario Expected behavior
Valid barcode The application accepts the value and stores the payload without the terminator.
Empty input The application rejects or ignores it and does not create a record.
ENTER suffix The application submits or accepts the value once.
TAB suffix Focus moves to the intended next control, and the value is kept.
No suffix The input remains available until the application processes it.
Rapid consecutive scans Each value is processed separately and is not concatenated with the previous one.
Wrong keyboard layout Unexpected characters are visible in the captured value and fail validation.
Duplicate scan The application follows its own duplicate rule, such as increment quantity or reject a replay.
Invalid barcode format The application shows the validation error for that format and does not store the value.
Lost input focus The application does not invent a barcode. The scan is absent or lands in the focused control, and the page stays in a safe state.

Run the valid, empty, ENTER, TAB, and no-suffix rows with the physical scanner and again with the emulator. Run the keyboard-layout, QR, and reconnect rows on the hardware. Those rows depend on the device, the label, or the operating-system layout, which simulated keystrokes do not reproduce.