zxing-js / library

Multi-format 1D/2D barcode image processing library, usable in JavaScript ecosystem.
https://zxing-js.github.io/library/
Apache License 2.0
2.51k stars 547 forks source link

Starting camera after resetting throws an error when using Firefox mobile #514

Open Evaldash opened 2 years ago

Evaldash commented 2 years ago

Describe the bug

Starting the scanner, after resetting it and using another camera, causes Firefox mobile to throw an error, that the video could not be started. No other browser I've tested throws such an error. Adding a 2 second delay after reset seems to make it work every time.

To Reproduce Steps to reproduce the behavior:

  1. Start the camera stream.
  2. Reset the qr scanner
  3. Start it again in the same function, programatically.

Expected behavior Camera feed appears in the video element, just like in Chrome.

Smartphone (please complete the following information):

Additional context Adding a 2 second delay before restarting the qr scanner seems to make it work.

Evaldash commented 2 years ago

Here's a snippet, basically I keep the available cameras in a variable, and switch between them with a single button:

$("#next-cam-button").on("click", function () {
    if (canChangeCam){
        canChangeCam = false;
        codeReader.reset();

        selectedDeviceId = getNextCamera();

        showLoader();

        if (isFirefox && isAndroid){ // firefox bugs out otherwise?
          delay(2000).then( () => startScan());
        }
        else{ startScan(); }
    }
})

function getNextCamera(){
  currentCamIndex++;
  if (currentCamIndex >= availableCameras.length){
    currentCamIndex = 0;
  }
  return availableCameras[currentCamIndex].deviceId;
}

function startScan(){
    codeReader.decodeFromVideoDevice(selectedDeviceId, 'camera-stream', (result, err) => {
      if (result) {
        console.log(result)
        lastScannedString = result.text;
      }
      if (err && !(err instanceof ZXing.NotFoundException)) {
        console.error("Error: " +err);
      }
    })
    console.log(`Started continous decode from camera with id ${selectedDeviceId}`)
}
github-actions[bot] commented 7 months ago

Stale issue message