Friday, 17 May 2019

How do I distinguish between a scanner input and keyboard input in Javascript?

I have gone through answers and came across two ways which can help in distinguishing between scanner and keyboard inputs. It can be done through:

  • Time Based: Scanner inputs are faster than manual keyboard inputs.

  • Prefix Based: Append a prefix to barcodes or scanners (inbuilt in scanner devices) and use it to identify the scanner inputs.

Here are the links: link 1, link 2 which I have used for the references.

The problem which I have run into is that whenever the user manually types some keyboard keys while the scanning event is being fired it gets added to scanner input and leads to inconsistent results.

Here is the code which I am using:

var BarcodeScannerEvents = function(){
  this.initialize.apply(this, arguments);
};

BarcodeScannerEvents.prototype = {
  initialize: function() {
    $(document).on({
      keypress: $.proxy(this._keypress, this)
    });
  },
  _timeoutHandler: 0,
  _inputString: '',
  _keypress: function (e){
    if(this._timeoutHandler){
      clearTimeout(this._timeoutHandler);
    }
    this._inputString += String.fromCharCode(e.which);
    //CHECKS FOR VALID CHARACTERS WHILE SCANNING 
    this._timeoutHandler = setTimeout($.proxy(function(){
      if(this._inputString.length <= 10){
        this._inputString = '';
        return;
      }
      $(document).trigger('barcodescanned', this._inputString);
      this._inputString = '';
    }, this), 20);
  }
};

new BarcodeScannerEvents();

The format for my barcode is: ~xxx-xxx-xxxxxx where x can be any number between 0-9. If a character which is a number is appended to the barcode it leads to wrong inserts in the database.

I have tried comparing the events from keyboard inputs and scanner inputs but to no avail. I have given a thought of appending extra characters before each digit and then invalidate the scanned barcode if consecutive numbers appear. But I don't feel this is best way to approach this problem. Can someone help me out here?



from How do I distinguish between a scanner input and keyboard input in Javascript?

No comments:

Post a Comment