Disable keyboard with HTML input and allow scanners

So first you need to understand that barcode scanners pretend to be keyboards. So they will trigger JS keystroke events just like real keyboards. The only way I can think of to separate the 2 is some timing-based heuristic (the idea being that nobody can type an entire 10-digit barcode in less than 0.1 seconds).

So basically, you would have some javascript that would do something along these lines:

  • (onkeydown) append the pressed key to a global string and start a timer with setTimeout (with very low delay, say 10 ms)
  • (onkeydown) append the pressed key as before, but don't start the timer again
  • in your setTimeout function, check if the string of keypresses is at least 3 keys (or longer, depending on the barcodes that you expect). If so, write the string to the input field. Otherwise, drop the string
  • rinse and repeat

It's gonna be ugly, but if you're really desperate, it might work

var delay = (function(){
   var timer = 0;
   return function(callback, ms){
      clearTimeout (timer);
      timer = setTimeout(callback, ms);
   };
})();

$("#txtInput").on("input", function() {
   delay(function(){
      if ($("#txtInput").val().length < 8) {
          $("#txtInput").val("");
      }
   }, 20 );
});

I kept thinking after I posted my reply to you for a solution because back in the days of DOS/Windows this used to be a pretty common request but not over the web.

What you can do is to setup your scanner and send as the beginning of a scan a set of string chars as the "starting point" for the scan and then some other chars as the end, I was thinking in something like this:

@@XX@@YOUR REAL SCAN GOES HERE@@YY@@\r

And then you can filter the content of that field at the ENTER char and check if it is coming from your scanner or not and then assign it. Not sure if your scanner supports pre-post-pending data to your scan but if it does it definitely does worth the try.


<script>    
setTimeout('timedRefresh()', 300000);   
setTimeout('refocus()', 1000);      
//********** KEYPRESS PREVENTION
$(document).ready(function(){
    $("#txtInput").keypress(function() {
        setTimeout('refocus()', 700)
    });
}); 

//********** PASTE PREVENTION $(document).ready(function(){
$(document).on("cut copy paste","#txtInput",function(e) {
    e.preventDefault();
    });  
}); 

When you press it clears every character. but you can use barcode scanner to key in your text. You are not allowed to paste also. 700ms timeout is what i believe the most optimized time for barcode to keyin the text and press enter.


<input type="number" id="txtInput">

That will enable only numbers to be inputed