Javascript:휴대용 바코드 스캐너를 가장 잘 읽는 방법은 무엇입니까?
핸드헬드 스캐너로 바코드를 스캔하여 Javascript로 결과를 처리할 수 있으면 좋겠습니다.
바코드 스캐너는 키보드처럼 작동합니다.스캔/변환된(바코드->번호) 데이터를 미가공(오른쪽?)으로 출력합니다.사실 결과만 보고 계속 진행하면 돼요.하지만 어떻게요?
작업하고 싶은 의사 코드는 다음과 같습니다.
$(document).on("scanButtonDown", "document", function(e) {
// get scanned content
var scannedProductId = this.getScannedContent();
// get product
var product = getProductById(scannedProductId);
// add productname to list
$("#product_list").append("<li>" + product.name + "</li>");
});
- 아이디어(프레임워크, 플러그인, 스니펫)가 있습니까?
- 바코드 스캐너(하드웨어) 권장 사항이 있습니까?
이것과 좋은 질문들을 찾았는데, 취급에 대해 좀 더 알고 싶습니다.내 경우 텍스트 영역에 초점을 맞추는 것만으로는 충분하지 않을 수도 있습니다.
하지 않습니다. 음음 you your 、 음 、 음 、 음 、 your 、 your your your your your like like 。scanButtonDown키보드와 똑같이 동작하는 HID 스캐너가 유일한 옵션입니다.스캐너 입력과 키보드 입력을 구별하려면 다음 두 가지 옵션이 있습니다.★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
타이머 베이스
스캐너의 문자 입력 속도는 사용자가 키보드로 입력할 수 있는 속도보다 훨씬 빠릅니다. 빨리 되는지 계산하고 을 버퍼링하여 .getProductsId기능.@Vitall은 바코드 스캐너 입력을 포착하기 위한 재사용 가능한 jQuery 솔루션을 작성했습니다. 바코드 스캔된 이벤트를 포착하기만 하면 됩니다.
프리픽스 베이스
대부분의 스캐너는 스캔한 모든 데이터에 접두사를 붙이도록 구성할 수 있습니다.접두사를 사용하여 모든 입력 감청을 시작할 수 있으며, 바코드를 받으면 입력 감청을 중지할 수 있습니다.
완전 공개:핸드헬드 스캐너를 만드는 Socket Mobile, Inc.의 컨설턴트로 일하고 있습니다.
많은 조사와 테스트를 거친 후, 가장 잘 작동한 것은 양식 입력에 초점을 맞추지 않고 바코드 스캐너에서 입력을 캡처하는 것이었습니다. listen을 듣다keydown ★★★★★★★★★★★★★★★★★」textInput벤트입입니니다
textInputpaste이벤트입니다. 그러면 바코드 데이터 전체가 포함됩니다.UPC를 사용합니다.e.preventDefault()바코드 데이터가 양식 입력에 삽입되지 않도록 합니다.
document.addEventListener('textInput', function (e){
if(e.data.length >= 6){
console.log('IR scan textInput', e.data);
e.preventDefault();
}
});
Android 4.4 및 7.0에서 CipherLab IR 스캐너를 사용하여 테스트한 적이 있습니다.
를 예keydown제 경우 폼 입력에 초점이 맞춰지지 않는 한 사용자가 바코드를 스캔하고 있다고 가정할 수 있습니다.
let UPC = '';
document.addEventListener("keydown", function(e) {
const textInput = e.key || String.fromCharCode(e.keyCode);
const targetName = e.target.localName;
let newUPC = '';
if (textInput && textInput.length === 1 && targetName !== 'input'){
newUPC = UPC+textInput;
if (newUPC.length >= 6) {
console.log('barcode scanned: ', newUPC);
}
}
});
스캔을 하는 것이 , " "를 수 있습니다.e.keyCode === 13 keydown이벤트 리스너
가 IR을 .textInput event와 유사한할 수 있습니다. 단말기가 그렇지 않은 경우 다음과 유사한 것을 방출하고 있는지 확인할 수 있습니다.
monitorEvents(document.body);
다음 모니터링 트릭을 찾았습니다.jQuery에서 요소에 의해 발생한 모든 이벤트를 기록하려면 어떻게 해야 합니까?
조금 늦었지만 여기 답변을 바탕으로 이 문제를 해결했습니다.
let code = "";
let reading = false;
document.addEventListener('keypress', e => {
//usually scanners throw an 'Enter' key at the end of read
if (e.keyCode === 13) {
if(code.length > 10) {
console.log(code);
/// code ready to use
code = "";
}
} else {
code += e.key; //while this is not an 'enter' it stores the every key
}
//run a timeout of 200ms at the first read and clear everything
if(!reading) {
reading = true;
setTimeout(() => {
code = "";
reading = false;
}, 200); //200 works fine for me but you can adjust it
}
});
바코드 스캐너는 키보드처럼 작동합니다.
기종에 따라 다릅니다.지금까지 사용한 것은 모두 키보드와 똑같이 동작합니다(최소한 컴퓨터에 관한 한).
스캔/변환된(바코드->번호) 데이터를 미가공(오른쪽?)으로 출력합니다.
키 코드를 출력합니다.
$(document).on("scanButtonDown"
당신은 아마 원할 것이다.keypress 아니라, 이에요.scanButtonDown.
이벤트 개체를 보고 누른 "키"를 확인합니다.
코드 전체가 스캔 된 시기를 확인하려면 , 「데이터의 끝」키(스페이스나 리턴등)를 취득하거나, 입력되고 있는 문자수를 세거나 할 필요가 있습니다.
여기는 잘 되고 있어요.
입력에 포커스가 있고 입력에 포커스가 없을 때 동작합니다.
on_scanner() // init function
function on_scanner() {
let is_event = false; // for check just one event declaration
let input = document.getElementById("scanner");
input.addEventListener("focus", function () {
if (!is_event) {
is_event = true;
input.addEventListener("keypress", function (e) {
setTimeout(function () {
if (e.keyCode == 13) {
scanner(input.value); // use value as you need
input.select();
}
}, 500)
})
}
});
document.addEventListener("keypress", function (e) {
if (e.target.tagName !== "INPUT") {
input.focus();
}
});
}
function scanner(value) {
if (value == '') return;
console.log(value)
}
HTML
<input type="text" id="scanner" placeholder="scanner">
모든 솔루션을 시도했지만 예상대로 작동하지 않았다.나는 angular 8을 사용하는 어플리케이션 onscan.js에서 가장 쉬운 솔루션을 찾았습니다.
매우 심플하고, 실장도입이 가능합니다.
각도 8의 경우 다음 단계를 따릅니다.
1.npm install onscan.displays --save
2. open angular.json, 스크립트 배열에 "node_model/onscan.min.model"로 엔트리를 추가합니다.
3. 컴포넌트 클래스에서 인터페이스 AfterView를 구현합니다.초기화
declare var onscan:any;
ngAfterViewInit(): void {
//Put focus to textbox and press scanner button
onScan.attachTo(document, {
suffixKeyCodes: [13], // enter-key expected at the end of a scan
reactToPaste: true, // Compatibility to built-in scanners in paste-mode (as opposed to keyboard-mode)
onScan: function (sCode, iQty) { // Alternative to document.addEventListener('scan')
console.log('Scanned: ' + iQty + 'x ' + sCode);
},
});
}
검색된 텍스트가 포크된 텍스트 상자 요소에 나타나는 것이 가장 좋습니다.
이게 도움이 됐으면 좋겠다.
리액트(React) 무무힘힘힘힘힘힘Hanz Herdel han han ENTER 。저 같은 경우에는 입력 내용을 폼으로 정리하여 제출 이벤트를 포착하고 디폴트를 방지하고 입력 값을 검색하는 것이 더 쉬웠습니다.
저는 바코드 길이를 확인하는 대신 어떤 유형의 바코드 길이를 처리하는 방식을 선호했습니다.
React에서의 대처 방법은 다음과 같습니다.
import { useState } from "react";
export default function Modal() {
const [repairArticles, setRepairArticles] = useState([]);
function handleBarcodeInput(e) {
e.preventDefault();
const input = e.target.querySelector("input");
const value = input.value;
setRepairArticles((prev) => {
return (prev = [...prev, value]);
});
input.value = "";
}
return (
<div>
<form onSubmit={(e) => handleBarcodeInput(e)} >
<input id="barcode-input" />
<button type="submit" className="hidden" />
</form>
<div className="mt-3">
{repairArticles.map((el, index) => {
return <p key={index}>{el}</p>;
})}
</div>
</div>
)
}
이것은, PosX 스캐너 또는 문자의 선두에 특수 기호를 추가할 수 있는 그 외의 스캐너를 사용하고 있는 경우의, Hanz Herdel 의 회답의 확장입니다.이 경우 칠드(~) 기호는 다음과 같습니다.
let barcode = "";
let reading = false;
document.addEventListener("keydown", e => {
//console.log(e.key);
if (e.key == 'Enter') {
if (barcode.length == 17) {
if (barcode.charAt(0) == '~') {
console.log(barcode);
barcode = "";
}
}
}
else {
if (e.key != 'Shift') {
barcode += e.key;
}
}
if (!reading) {
reading = true;
setTimeout( () => {
barcode = "";
reading = false;
}, 200);
}
}, true)
바코드 길이와 타임아웃 속도를 원하는 대로 변경할 수 있지만, 저는 이 방법이 완벽했습니다.
Vue 2 구현(vuejs 구문은 angular와 유사함):
BarcodeScanner.vue컴포넌트 코드는 다음과 같습니다.
<template>
<input type="hidden" name="_barcode" v-model="finalCode" />
</template>
<script>
export default {
props: {
onSuccess: {
type: Function,
required: true
},
minLength: {
type: Number,
default: () => 10
}
},
data() {
return {
code: "",
finalCode: "",
fromScanner: false,
reading: false
};
},
mounted() {
document.addEventListener("keypress", this.documentKeyboardListener);
},
destroyed() {
document.removeEventListener("keypress", this.documentKeyboardListener);
},
methods: {
documentKeyboardListener(e) {
if (e.target.nodeName !== 'BODY') return;
if (e.code === "Enter") {
if (this.reading && this.code.length > this.minLength) {
if (this.onSuccess)
this.onSuccess(this.code);
this.finalCode = this.code;
this.code = "";
this.fromScanner = true;
}
} else {
this.code += e.key; //while this is not an 'enter' it stores the every key
}
//run a timeout of 200ms at the first read and clear everything
if (!this.reading) {
this.reading = true;
setTimeout(() => {
this.code = "";
this.reading = false;
this.fromScanner = false;
}, 200); //200 works fine for me but you can adjust it
}
},
},
};
</script>
컴포넌트는 어디에서나 호출할 수 있습니다.
...
<barcode-scanner onSuccess="yourListener"/>
...
(JS 스캐너 코드는 Hanz Herdel에서 가져온 것입니다.)
바코드 스캔과 신용카드 스캔(jQuery 기반)을 처리하는 플러그인 작업을 막 시작했습니다.
https://github.com/ericuldall/jquery-pos
심플한 구현:
$(function(){
$(document).pos();
$(document).on('scan.pos.barcode', function(event){
var barcode = event.code;
//handle your code here....
});
});
지금까지 이 플러그인은 1종류의 스캐너와 숫자만을 포함한 코드로만 테스트되고 있습니다만, 이 플러그인과 함께 동작하지 않는 요건이 있으면 기꺼이 대응해 드리겠습니다.GITHUB 페이지를 확인하시고 한번 시도해 보세요.기부를 장려합니다.
E
var txt = "";
function selectBarcode() {
if (txt != $("#focus").val()) {
setTimeout('use_rfid()', 1000);
txt = $("#focus").val();
}
$("#focus").select();
setTimeout('selectBarcode()', 1000);
}
$(document).ready(function () {
setTimeout(selectBarcode(),1000);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="tag" id="focus" placeholder="Use handheld RFID scanner">
강화가 필요하지만 스캔한 데이터를 100ms 미만으로 전송하는 이 루틴은 실제 가동 중에 작동합니다.@jfbloom22와 다른 답변에 대한 영감과 모니터이벤트를 떠올리게 해 주셔서 감사합니다.
스캐너가 「HID 키보드」타입의 데이터(?)를 송신하도록 설정하고, 「Enter」로 종료하도록 설정할 필요가 있습니다.
순수 JavaScript 로직이지만 입력란에 집중할 필요 없이 스캔 데이터를 받아들일 수 있는 PCF(Power Apps Component Framework) 프로젝트용 TypeScript 앱으로 작성되었습니다.지구촌은 편의시설로 사용되었다.
public Scan(evt: Event): void {
const e:KeyboardEvent = evt as KeyboardEvent;
const timeDiff = e.timeStamp - CheckInPCF.LastTimeStamp;
CheckInPCF.LastTimeStamp = e.timeStamp; //"global"
//console.log(e.key + ': ' + timeDiff);
if (timeDiff < 100) {
if (e.key == 'Enter') {
//Assemble complete scan text
CheckInPCF.ScanText = CheckInPCF.FirstCharacterCandidate + CheckInPCF.ScanText; //.replace('\u000D','');
//console.log('finished: ' + CheckInPCF.ScanText);
CheckInPCF._this._notifyOutputChanged(); //Power Apps related
}
else {
CheckInPCF.ScanText += e.key;
}
}
else {
CheckInPCF.ScanText = '';
CheckInPCF.FirstCharacterCandidate = e.key;
}
}
이 코드는 문제 없습니다. 시도해 보십시오.
var barcode = '';
var interval;
document.addEventListener('keydown', function(evt) {
if (evt.code === 'F12'){
evt.preventDefault();
}
if (interval){
clearInterval(interval);
}
if (evt.code == 'Enter') {
if (barcode){
$('#barcode').val(barcode);
console.log(barcode);
}
barcode = '';
return;
}
if (evt.key != 'Shift'){
barcode += evt.key;
}
interval = setInterval(() => barcode = '', 20);
});
언급URL : https://stackoverflow.com/questions/21633537/javascript-how-to-read-a-hand-held-barcode-scanner-best
'programing' 카테고리의 다른 글
| JSON을 사용하여 JSON 데이터를 C#으로 역직렬화합니다.그물 (0) | 2023.03.14 |
|---|---|
| JSON 파일 생성을 스트리밍하려면 어떻게 해야 합니까? (0) | 2023.03.14 |
| Java 웹 애플리케이션용 Spring Boot의 단점은 무엇입니까? (0) | 2023.03.14 |
| WooCommerce Order API는 항상 빈 주문을 만듭니다. (0) | 2023.03.14 |
| 리액트 훅 - 변수와 useState 사용 (0) | 2023.03.14 |