0

I want to create a barcode scanner for products. I already saw an answer to that :

$(document).ready(function() {
       var barcode="";
   $(document).keydown(function(e) {

       var code = (e.keyCode ? e.keyCode : e.which);
       if(code==13)// Enter key hit
       {
           alert(barcode);
       }
       else if(code==9)// Tab key hit
       {
           alert(barcode);
       }
       else
       {
           barcode=barcode+String.fromCharCode(code);
       }
   });

   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

So, when I try that code, I press a rando key and after that enter. Then The code showes the key, I pressed first. Somebody else said before, that Barcode works like a keyboard.

But how can I now create the scanner, to scan products and (if possible) see the name of the product? Or is this code just not the code, I need for it and something else?

Adolf Weii
  • 23
  • 6
  • A barcode scanner is a device you can buy and attach to the USB port to behave like a USB keyboard, not something you create with javascript. – RalfFriedl Oct 07 '18 at 07:46
  • Can´t you do that with a camera? – Adolf Weii Oct 07 '18 at 07:50
  • Yes, you just have to create the image recognition for the barcode. Or if you're talking about a mobile phone, it might be possible to invoke an app for that purpose, assuming it is installed. – RalfFriedl Oct 07 '18 at 07:56

1 Answers1

-1

You can do with JS inside HTML page.

For barcode scanning you need a barcodescanner.js file :

(function ($) {
    $.fn.scannerDetection = function (options) {

        // If string given, call onComplete callback
        if (typeof options === "string") {
            this.each(function () {
                this.scannerDetectionTest(options);
            });
            return this;
        }

        // If false (boolean) given, deinitialize plugin
        if (options === false) {
            this.each(function () {
                this.scannerDetectionOff();
            });
            return this;
        }

        var defaults = {
            onComplete: false, // Callback after detection of a successfull scanning (scanned string in parameter)
            onError: false, // Callback after detection of a unsuccessfull scanning (scanned string in parameter)
            onReceive: false, // Callback after receiving and processing a char (scanned char in parameter)
            onKeyDetect: false, // Callback after detecting a keyDown (key char in parameter) - in contrast to onReceive, this fires for non-character keys like tab, arrows, etc. too!
            timeBeforeScanTest: 100, // Wait duration (ms) after keypress event to check if scanning is finished
            avgTimeByChar: 30, // Average time (ms) between 2 chars. Used to do difference between keyboard typing and scanning
            minLength: 6, // Minimum length for a scanning
            endChar: [9, 13], // Chars to remove and means end of scanning
            startChar: [], // Chars to remove and means start of scanning
            ignoreIfFocusOn: false, // do not handle scans if the currently focused element matches this selector
            scanButtonKeyCode: false, // Key code of the scanner hardware button (if the scanner button a acts as a key itself) 
            scanButtonLongPressThreshold: 3, // How many times the hardware button should issue a pressed event before a barcode is read to detect a longpress
            onScanButtonLongPressed: false, // Callback after detection of a successfull scan while the scan button was pressed and held down
            stopPropagation: false, // Stop immediate propagation on keypress event
            preventDefault: false // Prevent default action on keypress event
        };
        if (typeof options === "function") {
            options = { onComplete: options }
        }
        if (typeof options !== "object") {
            options = $.extend({}, defaults);
        } else {
            options = $.extend({}, defaults, options);
        }

        this.each(function () {
            var self = this, $self = $(self), firstCharTime = 0, lastCharTime = 0, stringWriting = '', callIsScanner = false, testTimer = false, scanButtonCounter = 0;
            var initScannerDetection = function () {
                firstCharTime = 0;
                stringWriting = '';
                scanButtonCounter = 0;
            };
            self.scannerDetectionOff = function () {
                $self.unbind('keydown.scannerDetection');
                $self.unbind('keypress.scannerDetection');
            }
            self.isFocusOnIgnoredElement = function () {
                if (!options.ignoreIfFocusOn) return false;
                if (typeof options.ignoreIfFocusOn === 'string') return $(':focus').is(options.ignoreIfFocusOn);
                if (typeof options.ignoreIfFocusOn === 'object' && options.ignoreIfFocusOn.length) {
                    var focused = $(':focus');
                    for (var i = 0; i < options.ignoreIfFocusOn.length; i++) {
                        if (focused.is(options.ignoreIfFocusOn[i])) {
                            return true;
                        }
                    }
                }
                return false;
            }
            self.scannerDetectionTest = function (s) {
                // If string is given, test it
                if (s) {
                    firstCharTime = lastCharTime = 0;
                    stringWriting = s;
                }

                if (!scanButtonCounter) {
                    scanButtonCounter = 1;
                }

                // If all condition are good (length, time...), call the callback and re-initialize the plugin for next scanning
                // Else, just re-initialize
                if (stringWriting.length >= options.minLength && lastCharTime - firstCharTime < stringWriting.length * options.avgTimeByChar) {
                    if (options.onScanButtonLongPressed && scanButtonCounter > options.scanButtonLongPressThreshold) options.onScanButtonLongPressed.call(self, stringWriting, scanButtonCounter);
                    else if (options.onComplete) options.onComplete.call(self, stringWriting, scanButtonCounter);
                    $self.trigger('scannerDetectionComplete', { string: stringWriting });
                    initScannerDetection();
                    return true;
                } else {
                    if (options.onError) options.onError.call(self, stringWriting);
                    $self.trigger('scannerDetectionError', { string: stringWriting });
                    initScannerDetection();
                    return false;
                }
            }
            $self.data('scannerDetection', { options: options }).unbind('.scannerDetection').bind('keydown.scannerDetection', function (e) {
                // If it's just the button of the scanner, ignore it and wait for the real input
                if (options.scanButtonKeyCode !== false && e.which == options.scanButtonKeyCode) {
                    scanButtonCounter++;
                    // Cancel default
                    e.preventDefault();
                    e.stopImmediatePropagation();
                }
                // Add event on keydown because keypress is not triggered for non character keys (tab, up, down...)
                // So need that to check endChar and startChar (that is often tab or enter) and call keypress if necessary
                else if ((firstCharTime && options.endChar.indexOf(e.which) !== -1)
                    || (!firstCharTime && options.startChar.indexOf(e.which) !== -1)) {
                    // Clone event, set type and trigger it
                    var e2 = jQuery.Event('keypress', e);
                    e2.type = 'keypress.scannerDetection';
                    $self.triggerHandler(e2);
                    // Cancel default
                    e.preventDefault();
                    e.stopImmediatePropagation();
                }
                // Fire keyDetect event in any case!
                if (options.onKeyDetect) options.onKeyDetect.call(self, e);
                $self.trigger('scannerDetectionKeyDetect', { evt: e });

            }).bind('keypress.scannerDetection', function (e) {
                if (this.isFocusOnIgnoredElement()) return;
                if (options.stopPropagation) e.stopImmediatePropagation();
                if (options.preventDefault) e.preventDefault();

                if (firstCharTime && options.endChar.indexOf(e.which) !== -1) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    callIsScanner = true;
                } else if (!firstCharTime && options.startChar.indexOf(e.which) !== -1) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    callIsScanner = false;
                } else {
                    if (typeof (e.which) != 'undefined') {
                        stringWriting += String.fromCharCode(e.which);
                    }
                    callIsScanner = false;
                }

                if (!firstCharTime) {
                    firstCharTime = Date.now();
                }
                lastCharTime = Date.now();

                if (testTimer) clearTimeout(testTimer);
                if (callIsScanner) {
                    self.scannerDetectionTest();
                    testTimer = false;
                } else {
                    testTimer = setTimeout(self.scannerDetectionTest, options.timeBeforeScanTest);
                }

                if (options.onReceive) options.onReceive.call(self, e);
                $self.trigger('scannerDetectionReceive', { evt: e });
            });
        });
        return this;
    }
})(jQuery);

For usecase inside HTML :

<script type="text/javascript">
$(document).scannerDetection({
    timeBeforeScanTest: 200, // wait for the next character for upto 200ms
    startChar: [120], // Prefix character for the cabled scanner (OPL6845R)
    endChar: [13], // be sure the scan is complete if key 13 (enter) is detected
    avgTimeByChar: 40, // it's not a barcode if a character takes longer than 40ms
    onComplete: function(barcode, qty) {
        console.log(barcode);
        console.log(qty);
       // barcode number code
       // qty scanned by barcode scanner 
    },
    onKeyDetect: function(event) {
        return false;
    }
});
</script>
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
  • Please share more details. Which parts of this code are neccessary to show the product name? What does this code do after all? – Nico Haase Sep 29 '22 at 14:46
  • If the barcode sticker has a name then this code will give you a name of that barcode sticker. – NIKUNJ PATEL Sep 30 '22 at 06:14
  • Please add all clarification to your answer by editing it. Usually, the barcode contains solely the EAN, doesn't it? – Nico Haase Sep 30 '22 at 07:01
  • In CODE_39 you can also put the name of product as barcode raw text data. Please check this once : https://www.zoho.com/in/inventory/free-barcode-generator/#:~:text=To%20create%20a%20barcode,details%20in%20the%20note%20box. – NIKUNJ PATEL Sep 30 '22 at 07:05
  • This question is not about using a specific type of barcode that might contain the name, but about a generic solution. Also, please add all clarification to your answer by editing it – Nico Haase Sep 30 '22 at 07:08