How can I scan a QR code from a webcam using ZXing in JS?

12.5k Views Asked by At

I couldn't set up the library following up the README examples on the main repository. I do not wan't to use ES6, AMD or any method that require build steps.

1

There are 1 best solutions below

0
On BEST ANSWER

You can get the latest version of the library from a CDN:

<script type="text/javascript" src="https://unpkg.com/@zxing/library@latest"></script>

With that, ZXing will be available in the web page, so you can use some code like this to scan from a webcam using the decodeFromVideoDevice method:

<video id="webcam-preview"></video>
<p id="result"></p>
<script>
  const codeReader = new ZXing.BrowserQRCodeReader();

  codeReader.decodeFromVideoDevice(null, 'webcam-preview', (result, err) => {
    if (result) {
      // properly decoded qr code
      console.log('Found QR code!', result)
      document.getElementById('result').textContent = result.text
    }

    if (err) {
      // As long as this error belongs into one of the following categories
      // the code reader is going to continue as excepted. Any other error
      // will stop the decoding loop.
      //
      // Excepted Exceptions:
      //
      //  - NotFoundException
      //  - ChecksumException
      //  - FormatException

      if (err instanceof ZXing.NotFoundException) {
        console.log('No QR code found.')
      }

      if (err instanceof ZXing.ChecksumException) {
        console.log('A code was found, but it\'s read value was not valid.')
      }

      if (err instanceof ZXing.FormatException) {
        console.log('A code was found, but it was in a invalid format.')
      }
    }
  })
</script>

This code will continuously scan the webcam video stream and try to idenitfy QR codes in it.