4

I want to implement the BarcodeDetector in an Angular app. I tested out the API with the following code:

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="./script.js"></script>
  </head>  
  <body>
    <button onclick="scan()">Click me</button>
    <img src="./barcode.gif">
    <pre></pre>
  </body>
</html>

JavaScript:

function scan() {
  const images = document.querySelectorAll('img');
  const pres = document.querySelectorAll('pre'); 
  try {
    pres[0].textContent += 'started\n';
      let barcodeDetector = new BarcodeDetector();
      pres[0].textContent += 'created and detecting\n';
      barcodeDetector.detect(images[0]).then(detectedCodes => {
      for (const barcode of detectedCodes) {      
        pres[0].textContent += barcode.rawValue  + '\n';
      }}).catch((e) => {
    pres[0].textContent += e + '\n';
  });
  } catch (e) {
    pres[0].textContent += e + '\n';
  }
}

and it works perfectly. On the PC I got a NotSupported error and the decoded barcode when I opened the page on my phone.

Since TypeScript is a superset of JavaScript I tought that it should be quite simple to port the code but, apparently it isn't. The HTML in the angular app pretty much the same. The component code is the following:

var BarcodeDetector: any;

@Component({
    templateUrl: './index.component.html'
})
export class IndexComponent {

    @ViewChild('imgRef')
    image: ElementRef;

    hasBarcodeDetector = '';
    errors = '';
    scanData = '';

    constructor() {
        try {
            this.hasBarcodeDetector = 'BarcodeDetector' in window ? 'true' : 'false';
            const barcodeDetector = new BarcodeDetector();
            barcodeDetector.detect(this.image.nativeElement).then(detectedCodes => {
                for (const barcode of detectedCodes) {
                    this.scanData += barcode.rawValue + '\n';
                }
            });
        } catch (e) {
            this.errors = e;
        }
    }
}

The check whether the detector exists works, because I get true, but both on PC and mobile I get the following error:

TypeError: (void 0) is not a constructor

I'm guessing it has something to do with the declaration of the decoder, but I really have no idea on what to do.

3
  • This doesn't seem to be fixed two years later. I'm also using typescript and am getting Property 'BarcodeDetector' does not exist on type 'Window & typeof globalThis'.ts(2339)
    – Soubriquet
    Aug 9, 2022 at 3:31
  • Hi! I'm struggling to make it work in Angular as well. Could you please tell me if you did figure it out in the end how to do it?
    – alex
    Jan 19, 2023 at 21:37
  • @alex I posted an answer, in case you're still looking Nov 21, 2023 at 3:18

2 Answers 2

2

I ran into the same question, and it took me a bit. Might not be absolutely perfect, but the following is working for me.

I'm wanting to support scanning in both cases, as this is only available on Mac, Android, and Chrome OS.

Hopefully it helps! I appreciate any feedback.

<div *ngIf="hasBarcodeDetectorApi" else useWindowsScanning>
  <video id="player" #player></video>

  <div>{{consoleMessage}}</div>
</div>

<ng-template #useWindowsScanning>
  <mso-camera-scan (scanEvent)="onScanNumber($event)" (cameraError)="onCameraError()"></mso-camera-scan>
</ng-template>

My full component, as even reading the barcode takes a bit of effort

import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';

import { BarcodeDetectorApi, BarcodeDetectorOptions } from './barcode.model';
import { SubSink } from 'subsink';
import { concatMap, from, timer } from 'rxjs';

// declare keyword tells browser it is defined elsewhere, which is how this works
// I'd like to move to the barcode.model file, but compile issues that would take time to figure
// eslint-disable-next-line @typescript-eslint/naming-convention, no-var
export declare var BarcodeDetector: typeof BarcodeDetectorApi;

@Component({
  selector: 'mso-barcode-detector',
  templateUrl: './barcode-detector.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BarcodeDetectorComponent implements OnInit, AfterViewInit, OnDestroy {
  @Output() scanEvent = new EventEmitter<string>();
  @Output() cameraError = new EventEmitter<void>();
  @ViewChild('player', { static: false }) player: ElementRef<HTMLVideoElement>;

  hasBarcodeDetectorApi = false;
  barcodeDetector: BarcodeDetectorApi;
  consoleMessage: string;
  private subsink = new SubSink();
  private mediaStream: MediaStream = null;

  constructor() {
    if (!!window['BarcodeDetector']) {
      /*
      BarcodeDetector API only available on Mac, Android, and Chrome OS as of this note
      If you are on Windows then return and use a backup method of checking for barcodes
      */
      this.hasBarcodeDetectorApi = true;
    }
  }

  ngOnInit(): void {
    if (!this.hasBarcodeDetectorApi) {
      return;
    }

    console.log('Using BarcodeDetector API');

    const options = {} as BarcodeDetectorOptions;
    options.formats = ['code_128'];
    this.barcodeDetector = new BarcodeDetector(options);
  }

  ngAfterViewInit(): void {
    if (!this.hasBarcodeDetectorApi) {
      return;
    }
    const constraints = {
      video: {
        facingMode: 'environment',
      },
    } as MediaStreamConstraints;
    navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
      // Attach the video stream to the video element and autoplay.
      this.player.nativeElement.srcObject = stream;
      this.mediaStream = stream;
      this.player.nativeElement.play().then(() => {
        this.startListeningToBarcodes();
      });
    });
  }

  ngOnDestroy(): void {
    if (this.mediaStream) {
      this.player.nativeElement.pause();
      this.mediaStream.getTracks().forEach(x => x.stop());
    }
    this.subsink.unsubscribe();
  }

  onScanNumber(barcode: string): void {
    this.scanEvent.emit(barcode);
  }

  onCameraError(): void {
    this.cameraError.emit();
  }

  private startListeningToBarcodes(): void {
    /*
      Now that we've started the video we need to check for a barcode in intervals
      as the detect function checks exactly once when you call it
      We want to continue to check until we find a valid barcode
    */
    this.subsink.sink = timer(250, 500).pipe(
      concatMap(() => from(this.barcodeDetector
        .detect(this.player.nativeElement)
        .then((barcodes) => {
          if (barcodes.length === 0) {
            return;
          }
          console.log(`found ${barcodes.length} barcodes`);
          barcodes.forEach((barcode) => {
            console.log(barcode.rawValue);
            this.onScanNumber(barcode.rawValue);
          });
        })
        .catch((err) => {
          this.consoleMessage = err;
          console.log(err);
          this.onCameraError();
        }))))
      .subscribe();
  }
}

Finally, the model to make it work

// cheating by defining what it would look like, no implementation
// interface doesn't like to define constructor or static very easily
export class BarcodeDetectorApi {
  static getSupportedFormats(): Promise<BarcodeFormat[]> {
    throw new Error('not implemented');
  }
  constructor(barcodeDetectorOptions?: BarcodeDetectorOptions) { }
  detect(image: ImageBitmapSource): Promise<DetectedBarcode[]> {
    throw new Error('not implemented');
  }
}

export interface BarcodeDetectorOptions {
  formats?: Array<BarcodeFormat>;
};

export interface Point2D {
  x: number;
  y: number;
};

export interface DetectedBarcode {
  boundingBox: DOMRectReadOnly;
  rawValue: string;
  format: BarcodeFormat;
  cornerPoints: ReadonlyArray<Point2D>;
};

export type BarcodeFormat
  = 'aztec'
  | 'code_128'
  | 'code_11'
  | 'code_39'
  | 'code_93'
  | 'codabar'
  | 'data_matrix'
  | 'ean_13'
  | 'ean_8'
  | 'itf'
  | 'pdf417'
  | 'qr_code'
  | 'micro_qr_code'
  | 'maxi_code'
  | 'upc_a'
  | 'upc_e'
  | 'gs1_composite'
  | 'gs1_databar'
  | 'gs1_databar_expanded'
  | 'gs1_databar_expanded_stacked'
  | 'gs1_databar_limited'
  | 'gs1_databar_omnidirectional'
  | 'gs1_databar_stacked'
  | 'gs1_databar_stacked_omnidirectional'
  | 'gs1_databar_truncated'
  | 'unknown';

1

I think with your variable you're accidentally overwriting the window.BarcodeDetector. Also note that you're not making use of the result of the feature detection. Feature detection, by the way, should happen differently now, as outlined in the recently updated article:

await BarcodeDetector.getSupportedFormats();
/* On a macOS computer logs
  [
    "aztec",
    "code_128",
    "code_39",
    "code_93",
    "data_matrix",
    "ean_13",
    "ean_8",
    "itf",
    "pdf417",
    "qr_code",
    "upc_e"
  ]
*/

This allows you to detect the specific feature you need, for example, QR code scanning:

if (('BarcodeDetector' in window) &&
    ((await BarcodeDetector.getSupportedFormats()).includes('qr_code'))) {
  console.log('QR code scanning is supported.');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.