Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

barcode scanner produces a "keypress" event only when the user is on an input box. What event to listen to when user is not on an input box?

Context:

I'm working on a web application that uses a barcode scanner device. Users scan barcodes, I redirect them to the appropriated page.

Problem:

The scan device I'm using triggers "keypress" events ONLY when the user is in a input box element

window.addEventListener("keypress", function (event) {
    // do something with the event
}

I would like to be able to scan barcodes from ANYWHERE in my application (even when I'm not in an input box). (Yes I know that the code above will fire for every character, I have a timer based algorithm to know if it's a barcode reader or a person typing.).

So far :

I looked at this, so I tried to replace the accepted solution's selector with a more general selector (window or document) without luck. Is there other events more appropriated for this task? I'm open to suggestions on doing it another way.

--EDIT-- :

After more research I came across this. The problem is that my view might not have any input. Just plain text

Thank you

like image 435
ObjectOrientedPirate Avatar asked Aug 16 '18 21:08

ObjectOrientedPirate


1 Answers

Here is for people that may want to know the answer:

For some reason, the following code works with all the scanner I've tested:

document.body.addEventListener("keydown", function(e) {
    // your handler here
}, true)

Note that the boolean true can also be false. Why it didn't work for "window.addEventListener" nor for "document.addEventListener"? I don't know.

like image 132
ObjectOrientedPirate Avatar answered Sep 18 '22 17:09

ObjectOrientedPirate