JS realizes the function of scanning QR code with code scanning gun

Time:2020-11-27

The scanning gun scans the QR code as follows:

Business needs to generate two-dimensional code data, and use the code gun to scan the data and upload to the server.

First on the code, and then improve the point of attention

this.start = new Date().getTime()
  let code = ''
  let lastTime, nextTime
  let lastCode, nextCode
  let that = this
  window.document.onkeypress = function (e) {
   if (window.event) { // IE
    nextCode = e.keyCode
   } else if (e.which) { // Netscape/Firefox/Opera
    nextCode = e.which
   }
   console.time()
   console.log('nextCode', nextCode)
   if (e.which === 13) {
    if ( code.length  < 3) return // the manual input time will not make the code length greater than 2, so only the code scanning gun will be available
    console.log(code)
    console.log ('scan code ends')
    console.timeEnd()
    that.parseQRCode (code) // get the input of the code scanning gun and do other operations
    code = ''
    lastCode = ''
    lastTime = ''
    return
   }
   nextTime = new Date().getTime()
   if (!lastTime && !lastCode) {
    console.log ('scan code begins... )
    code += e.key
   }
   If (lastcode & & lasttime & & nexttime - lasttime > 500) {// when there is a keypress event before code scanning, the prefix is prevented from missing
    console.log ('prevent missing initials... )
    code = e.key
   } else if (lastCode && lastTime) {
    console.log ('scanning code... )
    code += e.key
   }
   lastCode = nextCode
   lastTime = nextTime
  }

summary

The above is a small editor to introduce to you JS scan code gun scan two-dimensional code function, I hope to help you, if you have any questions, please leave me a message, small editor will reply you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!