Git Product home page Git Product logo

vue-barcode-scanner's Introduction

Vue Barcode Scanner

Barcode Scanner Plugin for Vue.js

Features

Usually in the market have a lot of barcode scanner. So we need to handle a lot of things to make this input right as it was for all scanner.

This plugin allows for better control of scanning inputs as speed of scanners lead to noisy and innacurate results. This plugin will allow you to use your already implemented barcode scanner in your project with better control and accuracy.

vue-barcode-scanner is a throttle for existing barcode scanners such as https://github.com/serratus/quaggaJS or https://github.com/hypery2k/cordova-barcodescanner-plugin/. vue-barcode-scanner is not a scanning tool on its own.

What's the problem

  • The listener will alway trigger for each character input, So we need to put it together and check when it's finished and ready to use.
  • Need to handle some special characters for some scanner, Because it's not the same for all scanner.

What this plugin do for you

  • Handle the listener for you and return the ready barcode to your callback just once when scanning is finished.
  • Handle special characters and return the complete barcode to you.

Update

  • Tab suffix barcode scanner compatibility
  • Listener for keypress instead of keydown (0.2)
  • New method to get previous barcode (0.2)
  • Listen to for all keypress not only textbox or textarea like previous version (0.3)
  • Check the input is come from barcode scanner by check elapsed time less than 500ms (0.3)
  • Support scanner that use "TAB" instead of "Enter" in the last scanned charactor (adding keydown event) (0.4)
  • Clear elapsed time when submit the barcode (0.4)
  • Change by pass elapsed time from 500ms to 30ms and change the logic to make scanner detection better (0.4)
  • Options to set scan sensitivity (it's elapsed time for each key scanned, default 100ms) (0.5)
  • New method to set scan sensitivity manually (0.5)
  • New option to require 'data-barcode' attribute for specific field input (0.6)

Dependencies

  • vue

Installation

Install via npm

npm install vue-barcode-scanner

Initiate

Inject plugin to your vue instance by Vue.use then initial it in your component that need to use barcode scanner

Default Injection

import Vue from 'vue'
import VueBarcodeScanner from 'vue-barcode-scanner'

...

// inject vue barcode scanner
Vue.use(VueBarcodeScanner)

Inject with option

// inject barcode scanner with option (add sound effect)
// sound will trigger when it's already scanned
let options = {
  sound: true, // default is false
  soundSrc: '/static/sound.wav', // default is blank
  sensitivity: 300, // default is 100
  requiredAttr: true, // default is false
  controlSequenceKeys: ['NumLock', 'Clear'], // default is null
  callbackAfterTimeout: true // default is false
}

Vue.use(VueBarcodeScanner, options)
  • Please note that if "requiredAttr" set to "true" you need to specific some input field with "data-barcode" and then only this input response to scanner
  • controlSequenceKeys: when a control key in this list is encountered in a scan sequence, it will be replaced with tags for easy string replacement
  • callbackAfterTimeout: this will fire the callback defined in the component once sensitivity ms has elapsed, following the last character in the barcode sequence. This is useful for scanners that don't end their sequences with ENTER and is backwards compatible with scanners that do.

Methods

init

Init method use for add event listener (keypress) for the scanner.

this.$barcodeScanner.init(callbackFunction, options)

options defaults to an empty object, {}, and can be safely ignored. See Advanced Usage for an example.

destroy

Destroy method is for remove the listener when it's unnecessary.

this.$barcodeScanner.destroy()

hasListener

Return the value that currently has a listener or not.

this.$barcodeScanner.hasListener() // return Boolean

getPreviousCode

Return last barcode scanned whatever your input is (In textbox currently). The last barcode will be replace when hit enter key.

this.$barcodeScanner.getPreviousCode() // return String

setSensitivity

Set limit of the time elapsed between each key stroke to distinguish between human typing and barcode scanner. Barcode scanner is determined by how fast between each key stoke. Argument is number of milliseconds.

this.$barcodeScanner.setSensitivity(200) // sets barcode scanner recognition sensitivity to 200 ms

Usage

In your component file (.vue) just for the component you need to listener for barcode.

  export default {
    created () {
      // Add barcode scan listener and pass the callback function
      this.$barcodeScanner.init(this.onBarcodeScanned)
    },
    destroyed () {
      // Remove listener when component is destroyed
      this.$barcodeScanner.destroy()
    },
    methods: {
      // Create callback function to receive barcode when the scanner is already done
      onBarcodeScanned (barcode) {
        console.log(barcode)
        // do something...
      },
      // Reset to the last barcode before hitting enter (whatever anything in the input box)
      resetBarcode () {
        let barcode = this.$barcodeScanner.getPreviousCode()
        // do something...
      }
    }
  }

Advanced (using eventBus)

  export default {
    data: () => ({
      loading: false
    }),
    created () {
      // Pass an options object with `eventBus: true` to receive an eventBus back
      // which emits `start` and `finish` events
      const eventBus = this.$barcodeScanner.init(this.onBarcodeScanned, { eventBus: true })
      if (eventBus) {
        eventBus.$on('start', () => { this.loading = true })
        eventBus.$on('finish', () => { this.loading = false })
      }
    },
    destroyed () {
      // Remove listener when component is destroyed
      this.$barcodeScanner.destroy()
    },
    methods: {
      // Create callback function to receive barcode when the scanner is already done
      onBarcodeScanned (barcode) {
        console.log(barcode)
        // do something...
      },
      // Reset to the last barcode before hitting enter (whatever anything in the input box)
      resetBarcode () {
        let barcode = this.$barcodeScanner.getPreviousCode()
        // do something...
      }
    }
  }

Disclaimer

This is NOT a barcode scanner. This is a scanner throttle to reduce innacurate scanner inputs.

vue-barcode-scanner's People

Contributors

bryantbj avatar dwoodworth-ud avatar joevandyk avatar kykungz avatar noomerzx avatar pangaunn avatar redpanda-bit avatar safinn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-barcode-scanner's Issues

Problem of implementation

Hye there, i don't undestand very well how you must implement that ?
I mean,I created a component just for that purpose but i don't know what i'm supposed to see ? I just noticed that it detects "Enter" inputs.
Does it use the camera or some sort just like QuaggaJS or must I ad an video element in the template ?

Integration Process

Hi, I've tried for many hours to implement the library without s results.

Can you provide any help?

I'm using vuejs 3 composition api + SFC <script setup>

Thanks in advance.

after routing to other component no event is triggered

Hi,

i registered the component in the root of my vue app. When i enter the site everything works as expected. but when i change the component via vue-router no event is fired when i scan a barcode.
The trick is to click anywhere on the page and after that the listener works and event is fired again as expected.

Do you have an idea?

Suggestion

I think that many people will be saved if there is also a sample of the part that obtains the barcode.

Why barcode scanner opens Chrome developer console in chrome?

I just bought a barcode reader from China model Honeywell HH400. It works perfectly when I use it other device. But now I use it in my web application and I am getting a problem. It always toggle Chrome developer console. I also tried scanning barcode into URL bar, and it does the same. Does it have an event to trigger F12 what? Or misconfiguration with the scanner that I don't know?

Listener not working on the electron wrapper

It perfectly works on the vue cli 3 production mode, but when I tried the vue electron module it works pretty well by running yarn elecrtron:serve but when I try to build it the electron production by running this. yarn electron:build the listener doesnt response and not trigger the data component.
Any ideas ?

bug!!

in your index.js

let attributes = {
previouseCode: '',
barcode: '',
setting: {
sound: false,
soundSrc: ''
},
callback: null,
hasListener: false,
pressedTime: []
}

and your code have attributes.previousCode ???
previouseCode = previousCode???

Not scanning after some time

My scanner implementation was working just fine and suddenly stop responding.

data() {
    return {
        loading: false,
    }
},
created() {
    let ui = JSON.parse(localStorage.getItem("user"))
    this.form.user_id = ui.id;
    //scanner
    const eventBus = this.$barcodeScanner.init(this.onBarcodeScanned, { eventBus: true })
    if (eventBus) {
        eventBus.$on('start', () => {
            this.loading = true;
            console.log('start') //not showing
        })
        eventBus.$on('finish', () => {
            this.loading = false;
            console.log('finished') //not showing
        })
    }
},
destroyed () {
    this.$barcodeScanner.destroy()
},
methods: {
    onBarcodeScanned (barcode) {
        console.log('barcode', barcode); //not showing
        this.tableCare();
    }
},

Any idea?

Chrome issue with keypress vs keydown and selected navigation buttons

First of all, thanks for creating this great plugin! Saved me some development time for sure, and I like the added touch of the sound option.

I wanted to report that I had an issue in Chrome on Mac with the Enter (keyCode = 13) only firing with a keydown event type sometimes instead of both keydown and a keypress. This would happen after a route change when a navigation button was still "selected". The only way I could get it to work reliably was to add && event.keyCode != 13 to the if statement on line 75 at the start of onInputScanned() to prevent the return.

There was also an apparent "loop" happening in navigation, where Vue-Router would attempt to route but then route right back to the current path (I'm using this to trigger routing based off scanning tracking/order barcodes). I discovered that not preventing the default action on the Enter key was allowing Chrome to fire the Enter event on that selected navigation button, thus routing right back to the path the button was wired to. So it would normally work the first time, and then appear to fail with the loop routing subsequent times. Again, interacting with the page via a mouse-click would effectively bring correct functionality back by "de-selecting" the menu nav button.

I was able to fix that issue by also adding || event.keyCode === 13 to the if statement on line 101 to allow the event.preventDefault() to fire with the Enter key event as well.

I've modified my own local code, and I could create a PR if needed, but first I wanted to get some feedback on whether these two changes might negatively affect other scenarios for other users?

can not work under firefox with quick search enabled and there is slash / character in barcode

Very helpful pulgin! But currently seems can not work under firefox with quick search enabled and there is slash / character in barcode

In latest version of Firefox , by default the quick search feature is enabled (Press the / slash key (forward slash character) the Quick Find bar will be open at the bottom), which means that if the barcode contains characters like slash, using current plugin we can NOT get the complete string value in Firefox!

The resolving method is to calling the preventDefault
method at the beginning of the function onInputScanned. Refer to this

Hoping for your feedback, thanks in advance!

Not work for devices that not support end Key (keycode: 13)

Thanks for your plug ins. It’s not work for devices that not support end Key (keycode: 13). I stoved the problem by making some changes in your code. here what I do

  1. I create local value timerId
  2. I cut the code from your function onInputScanned lines (77 – 88) and replace it with triggerBarcode();
  3. I create function triggerBarcode() and paste the code inside it

The final my new change are:

`
let timerId = -1;

function triggerBarcode() {

  if (timerId > -1)
    clearTimeout(timerId);

  timerId=-1;

  // scanner is done and trigger Enter/Tab then clear barcode and play the sound if it's set as true
  attributes.callback(attributes.barcode)
  // backup the barcode
  attributes.previousCode = attributes.barcode
  // clear textbox
  attributes.barcode = ''
  // clear pressedTime
  attributes.pressedTime = []
  // trigger sound
  if (attributes.setting.sound) {
    triggerSound()
  }
}

function onInputScanned (event) {
  // ignore other keydown event that is not a TAB, so there are no duplicate keys
  if (event.type === 'keydown' && event.keyCode != 9 ) {
    return
  }

  if (checkInputElapsedTime(Date.now())) {

    if ((event.keyCode === 13 || event.keyCode === 9) && attributes.barcode !== '') {

      triggerBarcode();
      // prevent TAB navigation for scanner
      if (event.keyCode === 9) {
        event.preventDefault()
      }
    } else {
      //reset timer
      if (timerId > -1)
        clearTimeout(timerId);
      timerId = setTimeout(triggerBarcode, attributes.setting.scannerSensitivity);

      // scan and validate each charactor
      attributes.barcode += event.key
    }
  }
}`

So please check it if it good to use

Using with QuaggaJS

Hello, I'm having trouble trying to figure out how to implement this alongside QuaggaJS. Does anyone have an example or some experience they wouldn't mind sharing? Thank you.

Question please

Is this supposed to work with external barcode scanner or uploaded images?

[Feature request] Before & After event

Thank for made this plugin it's easy to use and save me a lot of time, and I would like to request some features:

  • Before event: fire before barcode start scanning
  • After event: fire after barcode finished scanning

Thank again, these are my requests please let me know what you think about it

All fields in the screen are affected

Hi, I have other input fields in the screen (even in separate components) and every time tab key is pressed on any of them the scanner gets executed.
Is not possible to init the scanner with a particular field/s?

Barcode Scanners without Tab/Enter keypress

I use Zebra TC20 or TC25 Android barcode scanners - they don't finish with a final keypress.

I forked this and hacked in a fix to allow for a time (if more than barcode is larger than x in (x)ms)

Just figured that it may be useful to implement a proper fix for this.

Also I use this libary to handle usb RFID readers - works like a charm.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.