Barcode Scanner Emulator
How to Test QR Code Scanner Input in Web Applications
Many external QR-capable scanners use keyboard-wedge mode and type the decoded QR text into the focused field. Test that path by scanning a known payload and comparing it with the value the page received. Not every QR scanner types like a keyboard. Serial devices and camera decoders are different integrations, and browser keyboard events do not identify the physical scanner.
A QR code stores data. The scanner, or a camera decoder, turns that data into text. The web application then has to receive that text, decide when the scan is finished, and validate it. This guide is that application test. Generating labels, checking contrast, and confirming that a device can decode QR Code are covered in QR Code Testing: How to Test QR Code Scanners. General barcode forms, including EAN check digits, are covered in How to Test Barcode Scanners in Web Applications.
Test QR Scanner Input in 60 Seconds
Use a payload you chose, so a wrong character is obvious. This walkthrough uses QR-INPUT-TEST-12345.
- Open the QR Code Generator and generate a QR code for
QR-INPUT-TEST-12345. The generator runs in the browser. It does not contact the scanner. - Connect a QR-capable scanner that is set to keyboard-wedge mode. A 1D-only scanner cannot decode this symbol.
- Open the Barcode Input Tester.
- Click Start Test, or click the scan area, so the field has focus. The tester does not take focus by itself, and it does not open the scanner.
- Scan the QR code.
- Read the captured text and the character count.
- Compare that text with
QR-INPUT-TEST-12345. The match includes case, hyphens, and length. - Read the suffix. The tester reports ENTER, TAB, or None when the scanner sends one of those keys.
The tester records keyboard events the browser can see. It does not identify the USB device, read a serial port, or decode the QR image.
QR Scanner Input Modes
The same printed QR code can arrive through three different integrations. A test of one mode does not exercise the others.
Keyboard-wedge QR scanners
In USB HID keyboard mode, or Bluetooth HID keyboard mode, the operating system treats the scanner as a keyboard. After a decode, the scanner types the payload into whichever control has focus. A normal <input> or <textarea> can receive it. The page does not open the device. The HID Keyboard Wedge guide describes the keystroke sequence, prefixes, and suffixes.
Focus decides the destination. If the focused element is the document body, a button, or another frame, this field's listeners do not see the scan.
Serial QR scanners
A USB serial or virtual COM port scanner sends the decoded text as bytes to the process that opened the port. Focus does not choose that process. A field that only listens for keystrokes stays empty while a terminal on that port shows the payload.
Chromium-based browsers can open a user-selected port with the Web Serial API, in a secure context, after a user gesture. Firefox and Safari do not provide that API. A wedge scanner does not appear as a serial port. Port names, baud, and framing depend on the device and driver. USB HID vs Serial Barcode Scanners compares the two interfaces. The Barcode Input Tester cannot read a COM port.
Camera-based QR scanning
A camera integration captures an image and decodes the QR code in software. The page uses a camera API and a decoder. It does not receive keydown events for the payload. Phone-camera apps, in-page camera buttons, and a hardware imager that types into a field are three different products. Passing a wedge test does not mean the camera button works, and a successful camera decode does not mean a wedge scanner will type the same string.
Capture QR Scanner Input With JavaScript
The page below reads one focused field. Enter submits the form, and the Accept button uses that same submit handler, so one scan is processed once. Without an ENTER suffix, the text stays in the field until someone activates Accept. The captured payload is written with textContent, so characters such as < stay visible as text.
The example accepts three application formats: a ticket id such as QR-INPUT-TEST-12345, an http or https URL, or a JSON object. It records the scanned text. It does not navigate to a URL found in the QR code. A scanner that sends no Enter still works through the button. Tab moves through the label, the field, and the button as usual, because the script does not trap it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>QR input example</title>
</head>
<body>
<form id="qr-form">
<label for="qr">QR payload</label>
<input id="qr" name="qr" type="text" autocomplete="off" spellcheck="false">
<button type="submit">Accept</button>
</form>
<p id="status" role="status"></p>
<pre id="captured"></pre>
<script>
const form = document.querySelector('#qr-form')
const field = document.querySelector('#qr')
const status = document.querySelector('#status')
const captured = document.querySelector('#captured')
if (
!(form instanceof HTMLFormElement) ||
!(field instanceof HTMLInputElement) ||
!(status instanceof HTMLElement) ||
!(captured instanceof HTMLElement)
) {
throw new Error('QR form markup is missing.')
}
const accepted = new Set()
function classify(raw) {
if (/[\u0000-\u001F\u007F]/.test(raw)) {
return { status: 'invalid', message: 'Control character in the QR payload.' }
}
const value = raw.trim()
if (!value) {
return { status: 'empty' }
}
if (value.length > 2048) {
return { status: 'invalid', message: 'QR payload is longer than this form accepts.' }
}
if (/^QR-[A-Z0-9-]{1,64}$/.test(value)) {
return { status: 'ok', value }
}
if (value.startsWith('{')) {
try {
const data = JSON.parse(value)
if (!data || typeof data !== 'object' || Array.isArray(data)) {
return { status: 'invalid', message: 'QR JSON must be an object.' }
}
return { status: 'ok', value }
} catch {
return { status: 'invalid', message: 'QR text is not valid JSON.' }
}
}
if (value.startsWith('http://') || value.startsWith('https://')) {
try {
const url = new URL(value)
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
return { status: 'invalid', message: 'Only http and https URLs are accepted.' }
}
return { status: 'ok', value }
} catch {
return { status: 'invalid', message: 'The QR text is not a valid URL.' }
}
}
return { status: 'invalid', message: 'Unexpected QR payload.' }
}
form.addEventListener('submit', (event) => {
event.preventDefault()
const outcome = classify(field.value)
if (outcome.status === 'empty') {
status.textContent = 'No QR payload received.'
field.focus()
return
}
if (outcome.status === 'invalid') {
status.textContent = outcome.message
captured.textContent = ''
field.focus()
return
}
if (accepted.has(outcome.value)) {
status.textContent = 'Already accepted ' + outcome.value
field.value = ''
field.focus()
return
}
accepted.add(outcome.value)
captured.textContent = outcome.value
status.textContent = 'Accepted ' + outcome.value
field.value = ''
field.focus()
})
</script>
</body>
</html>
Save the file and open it in a desktop browser. Click the field before scanning. autocomplete="off" reduces the chance that a saved value replaces the scan. The label and the button remain available, so a person can type a payload without a scanner.
Handle Enter in the form submit event only. A second keydown listener for Enter records the same scan twice. preventDefault() keeps the browser on this page. Clear the field after a decision so the next scan does not append to the previous text.
A QR payload can contain a line break. A wedge scanner often types that break as Enter. In a one-line input, the form can submit at the first line and drop the rest. Use a textarea, or a serial reader that keeps the bytes, when the application must accept multi-line text. Confirm that behaviour with a QR code whose payload includes a newline.
Handling QR Payloads
A QR symbol does not promise an application format. The same symbology can carry any of these:
- Plain text, such as
QR-INPUT-TEST-12345. - A URL.
- An identifier chosen by the application.
- A structured payload such as a ticket number plus a location code.
- JSON text, when the application defined that encoding.
The scanner transmits the decoded characters. It does not check that they match a ticket rule, a product catalog, or a JSON schema. Validate the string in the page, and validate it again on the server. The posted value is ordinary user input. The browser cannot prove that a scanner produced it.
Validate QR Input
Do not assume a QR payload is numeric. EAN-13 rules do not apply. Treat the text as untrusted: display it as text, and do not assign it to location, innerHTML, or a script URL.
Empty values. A bare Enter, or Accept on a blank field, should not create a record. trim() also rejects a payload that is only spaces.
Unexpected characters. Compare the received string with the known QR content. A keyboard-layout mismatch often changes punctuation while the length stays the same. Reject characters the format does not allow, and show the reason in the status text.
Payload length. Enforce the maximum your application stores. maxlength on the input truncates a longer scan with no error. Set it only when every accepted payload fits, and compare the tester's character count with the field when a value looks short.
Required prefixes. A prefix check belongs to the application. This ticket rule accepts QR- plus uppercase letters, digits, and hyphens:
function isTicketId(value) {
return /^QR-[A-Z0-9-]{1,64}$/.test(value)
}
Strip a scanner prefix only when that scanner is configured to send one exact prefix and the application does not store it. An AIM symbology identifier is data until you decide otherwise.
Application-specific formats. Keep the rule next to the format. A ticket form, a URL allow-list, and a JSON object need different checks. One numeric pattern will reject valid QR text.
Duplicate scans. One physical scan can hit two listeners. Use a single completion path, as the example does. A second trigger pull is a separate event. The example rejects a payload it has already accepted. A warehouse form might increment a quantity instead. Test the rule your application documents.
Malformed JSON. JSON.parse throws on incomplete text. Check the shape after a successful parse. An array or a bare number can be valid JSON and still be the wrong type:
function readJsonObject(value) {
try {
const data = JSON.parse(value)
if (!data || typeof data !== 'object' || Array.isArray(data)) {
return { ok: false, message: 'QR JSON must be an object.' }
}
return { ok: true, data }
} catch {
return { ok: false, message: 'QR text is not valid JSON.' }
}
}
Unexpected URLs. Parse the URL to see whether it is usable, then keep the scanned string if the test must match the QR payload exactly. URL.href can add a slash or change encoding. Accept only the schemes the application intends. Do not open the URL as a side effect of the scan:
function readWebUrl(value) {
let url
try {
url = new URL(value)
} catch {
return { ok: false, message: 'The QR text is not a valid URL.' }
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
return { ok: false, message: 'Only http and https URLs are accepted.' }
}
return { ok: true, value }
}
Control characters. Reject ASCII control characters in a keyboard payload so a hidden prefix remains visible in the status text. CR and LF are control characters. On a wedge scanner, Enter and Tab are keys. They are not characters inside a normal text input. A serial payload may still contain 0x0D or 0x0A bytes. Strip those at the serial framing boundary, and do not remove a CR that belongs in the middle of a multi-line payload.
ENTER and TAB Suffixes
A suffix is optional scanner configuration. It is not part of the QR symbol. ENTER vs TAB Suffixes in Barcode Scanners shows how to tell the keys apart. Read the suffix in the input tester, then make the page match the scanners you deploy.
ENTER submits a one-line text field's form in current browsers. Use that when one scan should commit the value. Call preventDefault() on submit when the page should stay in place.
TAB moves focus to the next control. Read the value in keydown while the field still has focus. Leave the default action in place when the next field should receive focus. Ignore Shift+Tab so a keyboard user can move backward.
No suffix leaves the payload in the field. The Accept button in the example is the completion path. An inactivity timer can guess that a pause means the scan ended. That timer is a heuristic: a slow Bluetooth burst and a fast typist can both cross the same gap. Prefer a configured suffix when the workflow needs a hard end.
CR and LF are bytes. A keyboard Enter is event.key === "Enter". Those are not interchangeable. A listener that only strips \r from an input value will not see a wedge Enter, because the character was never inserted. A listener that only watches event.key will not split a serial buffer on 0x0D. Some devices send NumPad Enter. event.key is still "Enter". Check event.key, not only event.code === "Enter".
The suffix can change when someone scans a configuration barcode from the device manual. Retest Enter, Tab, and no suffix after any configuration change. Do not invent a programming barcode. Use the manual for that model.
Debug Keyboard Events
When the stored text is wrong, inspect the events in this order.
keydown. Fires for every key, including Enter and Tab, before the browser inserts a character or moves focus. Read the terminator here.
input. Fires after a printable character changes the field. It does not fire for Enter or Tab on a text input.
event.key. The character or key name after the operating system applies the keyboard layout.
event.code. The physical key, such as Digit1 or Numpad1. It can stay the same when a layout mismatch changes event.key.
Focus. Log document.activeElement before the scan. If it is not the QR field, the rest of the trace describes the wrong control. An iframe has its own focus.
Order. For a wedge scan into a text field, printable keydown events are followed by input updates, then a final keydown for Enter or Tab when that suffix is configured. change fires when the field commits, usually on blur. A scan that leaves focus in the same field does not produce change at the end. Do not use change as the only completion signal.
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 hardware identification. A fast typist, autofill, or the emulator can land on the scanner side of that threshold. A delayed Bluetooth scan can look like typing. Assert the payload and the suffix. Treat timing as a clue.
The Keyboard Event Tester lists each keydown and keyup with key, code, modifiers, and timestamps. The log is browser events. It is not raw USB traffic.
Test Without a Physical QR Scanner
Application logic can be tested before a scanner is on the desk.
- Type
QR-INPUT-TEST-12345into the field and activate Accept. That checks validation and display. It does not check decode or suffixes. - Drive the same field from a browser automation tool, as the next section does.
- Use Barcode Scanner Emulator when you need scanner-style typing. The desktop app sends a value you enter, with a typing delay and a suffix of none, ENTER, or TAB, into the focused application. It reproduces the keyboard path. It does not photograph a QR image, decode a symbol, or create a virtual COM port.
Hardware is still required for optical and device behaviour: whether that scanner can read the displayed or printed code, whether QR symbology is enabled, keyboard layout, suffix configuration, and serial or vendor-SDK modes. The emulator is the right check for the keyboard path. It is the wrong check for proving that a device reads a particular QR code.
Automate QR Input Tests
The following Playwright tests drive the example page. They type into the field the way a wedge scanner would, then assert application behaviour. They do not open USB devices. @playwright/test is a reader dependency. This site does not require it.
Save the HTML example as qr-form.html next to this test.
import { readFileSync } from 'node:fs'
import { expect, test } from '@playwright/test'
const html = readFileSync(new URL('./qr-form.html', import.meta.url), 'utf8')
async function openForm(page) {
await page.setContent(html)
}
test('accepts a known QR payload once', async ({ page }) => {
await openForm(page)
const field = page.getByLabel('QR payload')
await field.pressSequentially('QR-INPUT-TEST-12345')
await field.press('Enter')
await expect(page.getByRole('status')).toHaveText('Accepted QR-INPUT-TEST-12345')
await expect(page.locator('#captured')).toHaveText('QR-INPUT-TEST-12345')
})
test('rejects an unexpected payload', async ({ page }) => {
await openForm(page)
const field = page.getByLabel('QR payload')
await field.pressSequentially('not-a-ticket')
await field.press('Enter')
await expect(page.getByRole('status')).toHaveText('Unexpected QR payload.')
await expect(page.locator('#captured')).toBeEmpty()
})
test('commits on ENTER and rejects a duplicate scan', async ({ page }) => {
await openForm(page)
const field = page.getByLabel('QR payload')
await field.pressSequentially('QR-INPUT-TEST-12345')
await field.press('Enter')
await field.pressSequentially('QR-INPUT-TEST-12345')
await field.press('Enter')
await expect(page.getByRole('status')).toHaveText('Already accepted QR-INPUT-TEST-12345')
await expect(page.locator('#captured')).toHaveText('QR-INPUT-TEST-12345')
})
test('does not capture keys while the field is unfocused', async ({ page }) => {
await openForm(page)
await page.getByRole('button', { name: 'Accept' }).focus()
await page.keyboard.type('QR-INPUT-TEST-12345')
await expect(page.getByLabel('QR payload')).toHaveValue('')
await expect(page.locator('#captured')).toBeEmpty()
await expect(page.getByRole('status')).toHaveText('')
})
test('shows unexpected characters as text', async ({ page }) => {
await openForm(page)
const payload = '<img src=x onerror=alert(1)>'
const field = page.getByLabel('QR payload')
await field.fill(payload)
await page.getByRole('button', { name: 'Accept' }).click()
await expect(page.getByRole('status')).toHaveText('Unexpected QR payload.')
await expect(page.locator('#captured img')).toHaveCount(0)
await expect(page.locator('img')).toHaveCount(0)
})
pressSequentially inserts characters into the focused field. It is not a USB gadget. The unexpected-character test uses fill because the goal is the validation message and the absence of an injected element. Extend the file with a URL case and a JSON case when those formats are in the build you ship. A URL assertion should compare the captured text with the original QR string.
QR Scanner Test Matrix
Run these against the application under test. The sample page above covers the ticket, URL, JSON, duplicate, empty, and unexpected-character rows. A numeric-only or multi-line application needs its own expected result.
| Scenario | Expected result |
|---|---|
| Plain text QR | Exact value received |
| URL QR | Complete URL captured, and the page does not navigate to it |
| Numeric QR | Digits preserved |
| Special characters | Correct characters received |
| JSON payload | Data captured and validated |
| ENTER suffix | Processing occurs once |
| TAB suffix | Focus behaviour handled |
| No suffix | Application uses an alternative completion mechanism |
| Duplicate scan | Application applies duplicate-handling rules |
| Invalid payload | Validation error displayed |
| Missing focus | Application handles absent input safely |
| Long payload | No unintended truncation |
Also scan a payload that contains a newline if the product must store one. Record whether the field received every line.
Troubleshooting
Start with a known payload in the input tester. If the tester's value is already wrong, the page is not the first fault. If the tester's value is right and the application is wrong, the fault is focus, validation, or event handling. Barcode Scanner Not Working is the broader device checklist. How to Test Barcode Scanner Input covers focus, layout, and POS workflows beyond this form.
Scanner beeps but no input appears
A beep usually means the scanner decoded a symbol. It does not mean the page received the text. Confirm keyboard-wedge mode. Serial and camera modes will not type into the field. Click the field so document.activeElement is that input, then scan again. A disabled, read-only, or hidden field can ignore the keys.
QR scanner works in Notepad but not the browser
The device is typing. The page is not accepting those keys. Check focus, a keydown listener that calls preventDefault() on printable keys, and a listener that only handles paste. Wedge input does not fire a paste event. Compare the tester result with the application field.
Scanner reads barcodes but not QR codes
The device may be 1D-only, or the QR symbology may be disabled. The page cannot fix that. Confirm 2D support and enable QR Code from the device manual, using the checks in QR Code Testing: How to Test QR Code Scanners. A successful Code 128 scan only proves the keyboard path.
Incorrect characters
Scan QR-INPUT-TEST-12345 first. If that matches and a URL or JSON payload does not, the layout is changing punctuation such as :, /, {, or ". Compare event.key with event.code in the Keyboard Event Tester, and see Barcode Scanner Wrong Keyboard Layout. Match the scanner's keyboard layout to the operating system.
ENTER submits the form twice
The browser submits the form, and a keydown listener also handles Enter. Keep one completion path and call preventDefault() there. A second physical scan is a different failure. The status text in the example says the payload was already accepted. If the first scan itself creates two records, look for two listeners before changing the scanner.
QR input is truncated
Compare the character count in the input tester with the value in the field. A maxlength attribute, an input mask, or preventDefault() on character keys can cut the string. A newline inside the QR payload can submit a one-line input early. Some scanners also limit how many characters they type. Raise that limit from the device manual when the tester, not only the application, shows a short value. Barcode Scanner Missing ENTER covers the related case where the payload arrives and the form never commits.
Scanner cannot read a QR code on screen
Confirm the scanner is a 2D imager. Raise the display brightness, increase the code size, and keep the quiet zone clear of text and borders. Glare, a dim phone screen, and a code that is too dense for the working distance are optical problems. Print the same payload if the screen read keeps failing. The application test still uses the known string once any scan produces text.