javascriptjqueryajaxangularjsbarcode-scanner

Javascript: How to read a hand held barcode scanner best?


I'd like to be able to scan barcodes via a hand held scanner and handle the results with Javascript.

A barcode-scanner works almost like a keyboard. It outputs the scanned/translated (barcode->number) data raw (right?). Actually I just need to catch the output and proceed. But how?

Here's some pseudocode I'd like to make work:

$(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>");
});

I found this and this good questions but I'd like to get more information about the handling. Just to focus a textarea may be not enough in my case.


Solution

  • Your pseudo code won't work, because you don't have access to the scanner to catch events like scanButtonDown. Your only option is a HID scanner, which behaves exactly like a keyboard. To differentiate scanner input from keyboard input you have two options: Timer-based or prefix-based.

    Timer-based

    The scanner is likely to input characters much quicker than a user can (sensibly) with a keyboard. Calculate how quickly keystrokes are being received and buffer fast input into a variable to pass to your getProductsId function. @Vitall wrote a reusable jQuery solution for catching barcode scanner input, you would just need to catch the onbarcodescanned event.

    Prefix-based

    Most scanners can be configured to prefix all scanned data. You can use the prefix to start intercepting all input and once you've got your barcode you stop intercepting input.

    Full disclosure: I work as a consultant to Socket Mobile, Inc. who make handheld scanners.