[removed] How to read a hand held barcode scanner best?

后端 未结 9 1728
温柔的废话
温柔的废话 2020-12-02 08:38

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

9条回答
  •  不思量自难忘°
    2020-12-02 08:52

    OK, so here's how I did it. I set up the scanner, to add a prefix (In my case, I used Ctrl+2 or the ascii code 002 (a control code) so it couldn't easily be entered via keyboard), and an ENTER, (Feel free to change this to use something like Ctrl+3 or ascii code 003 after each barcode scan, if your barcode data may contain enters). In jQuery, I capture the keypress event, and look for the prefix. I then, capture everything into a string, and then fire a custom event, that my app can listen for. Because I'm preventing the keypress event, the user can be in a text field, and scan a barcode, which can trigger an event without affecting anything they're doing.

    Additionally, each barcode has a 1 digit prefix that we use, to identify the type of barcode scanned. Examples:

    • E: Employee Badge
    • S: Supervisor Badge
    • I: Item Number
    let barcodeRead = '';
    let readingBarcode = false;
    
    let handleKeyPress = (e) => {
        if (e.keyCode === 2) {
            // Start of barcode
            readingBarcode = true;
            e.preventDefault();
            return;
        }
    
        if (readingBarcode) {
            e.preventDefault();
    
            if (e.keyCode === 13) { // Enter
                readingBarcode = false;
                const evt = $.Event('barcodeScan');
                evt.state = {
                    type: barcodeRead.substr(0, 1),
                    code: barcodeRead.substr(1),
                };
                $(window).trigger(evt);
                barcodeRead = '';
                return;
            }
    
            // Append the next key to the end of the list
            barcodeRead += e.key;
        }
    }
    
    $(window).bind('keypress', handleKeyPress);
    

    Because of this prefix, I can now identify the type of barcode, and see if it should be handled on this page. Example:

    $(window).bind('barcodeScan', (e) => {
        if (e.state.type !== 'E') {
            alert('Please scan your employee badge only!');
        } else {
            $('#employee-badge').val(e.state.code);
        }
    });
    

提交回复
热议问题