Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(barcode-scanning): add web support #52

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/rotten-garlics-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@capacitor-mlkit/barcode-scanning': minor
---

feat: add web support
8 changes: 8 additions & 0 deletions packages/barcode-scanning/src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ export interface StartScanOptions {
* @since 0.0.1
*/
lensFacing?: LensFacing;
/**
* The HTML video element to use for the camera preview.
*
* Only available on Web.
*
* @since 5.1.0
*/
videoElement?: HTMLVideoElement;
}

/**
Expand Down
82 changes: 78 additions & 4 deletions packages/barcode-scanning/src/web.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CapacitorException, ExceptionCode, WebPlugin } from '@capacitor/core';

import type {
BarcodeScannedEvent,
BarcodeScannerPlugin,
IsSupportedResult,
IsTorchAvailableResult,
Expand All @@ -11,17 +12,64 @@ import type {
ScanResult,
StartScanOptions,
} from './definitions';
import { BarcodeValueType } from './definitions';

export class BarcodeScannerWeb
extends WebPlugin
implements BarcodeScannerPlugin
{
async startScan(_options?: StartScanOptions): Promise<void> {
throw this.createUnavailableException();
public static readonly ERROR_VIDEO_ELEMENT_MISSING =
'videoElement must be provided.';
private readonly _isSupported = 'BarcodeDetector' in window;
private intervalId: number | undefined;
private stream: MediaStream | undefined;

async startScan(options?: StartScanOptions): Promise<void> {
if (!this._isSupported) {
this.throwUnsupportedError();
}
if (!options?.videoElement) {
throw new Error(BarcodeScannerWeb.ERROR_VIDEO_ELEMENT_MISSING);
}
this.stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: {
ideal: 'environment',
},
},
audio: false,
});
options.videoElement.srcObject = this.stream;
await options.videoElement.play();
const barcodeDetector = new window.BarcodeDetector({
formats: ['qr_code'],
});
this.intervalId = window.setInterval(async () => {
const barcodes = await barcodeDetector.detect(options.videoElement);
if (barcodes.length === 0) {
return;
} else {
for (const barcode of barcodes) {
this.handleScannedBarcode(barcode);
}
}
}, 1000);
}

async stopScan(): Promise<void> {
throw this.createUnavailableException();
if (!this._isSupported) {
this.throwUnsupportedError();
}
if (this.intervalId) {
window.clearInterval(this.intervalId);
this.intervalId = undefined;
}
if (this.stream) {
this.stream.getTracks().forEach(track => {
track.stop();
});
this.stream = undefined;
}
}

async readBarcodesFromImage(
Expand All @@ -35,7 +83,9 @@ export class BarcodeScannerWeb
}

async isSupported(): Promise<IsSupportedResult> {
throw this.createUnavailableException();
return {
supported: this._isSupported,
};
}

async enableTorch(): Promise<void> {
Expand Down Expand Up @@ -76,4 +126,28 @@ export class BarcodeScannerWeb
ExceptionCode.Unavailable,
);
}

private throwUnsupportedError(): never {
throw this.unavailable(
'Barcode Detector API not available in this browser.',
);
}

private handleScannedBarcode(barcode: any): void {
const result: BarcodeScannedEvent = {
barcode: {
displayValue: barcode.rawValue,
rawValue: barcode.rawValue,
format: barcode.format,
valueType: BarcodeValueType.Unknown,
},
};
this.notifyListeners('barcodeScanned', result);
}
}

declare global {
interface Window {
BarcodeDetector: any;
}
}