5.1.16 β€’ Published 9 months ago

@projectleannation/barcode-scanning v5.1.16

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
9 months ago

@projectleannation/barcode-scanning

Unofficial Capacitor plugin for ML Kit Barcode scanning.^1

Features

  • 🧩 Optional ready-to-use interface without webview customizations
  • 🏎️ Extremely fast
  • πŸ“· Scan multiple barcodes at once
  • ⏺️ Define detection area
  • 🏞️ Reading barcodes from images
  • πŸ”¦ Torch and Autofocus support
  • πŸ”‹ Supports Android and iOS

For a complete list of supported barcodes, see BarcodeFormat.

Demo

A working example can be found here: https://github.com/robingenz/capacitor-mlkit-plugin-demo

Android

Guides

Installation

npm install @projectleannation/barcode-scanning
npx cap sync

Android

This API requires the following permissions be added to your AndroidManifest.xml before the application tag:

<!-- To get access to the camera. -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- To get access to the flashlight. -->
<uses-permission android:name="android.permission.FLASHLIGHT"/>

You also need to add the following meta data in the application tag in your AndroidManifest.xml:

<meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="barcode_ui"/>
<!-- To use multiple models: android:value="face,model2,model3" -->

Variables

This plugin will use the following project variables (defined in your app’s variables.gradle file):

  • $androidxCameraCamera2Version version of com.google.mlkit:barcode-scanning (default: 1.1.0)
  • $androidxCameraCoreVersion version of com.google.mlkit:barcode-scanning (default: 1.1.0)
  • $androidxCameraLifecycleVersion version of com.google.mlkit:barcode-scanning (default: 1.1.0)
  • $androidxCameraViewVersion version of com.google.mlkit:barcode-scanning (default: 1.1.0)
  • $mlkitBarcodeScanningVersion version of com.google.mlkit:barcode-scanning (default: 17.1.0)
  • $playServicesCodeScannerVersion version of com.google.mlkit:barcode-scanning (default: 16.0.0)

iOS

Add the NSCameraUsageDescription key to the ios/App/App/Info.plist file, which tells the user why the app needs to use the camera:

+ <key>NSCameraUsageDescription</key>
+ <string>The app enables the scanning of various barcodes.</string>

Configuration

No configuration required for this plugin.

Demo

A working example can be found here: robingenz/capacitor-mlkit-plugin-demo

Usage

import {
  BarcodeScanner,
  BarcodeFormat,
  LensFacing,
} from '@projectleannation/barcode-scanning';

const startScan = async () => {
  // The camera is visible behind the WebView, so that you can customize the UI in the WebView.
  // However, this means that you have to hide all elements that should not be visible.
  // You can find an example in our demo repository.
  // In this case we set a class `barcode-scanner-active`, which then contains certain CSS rules for our app.
  document.querySelector('body')?.classList.add('barcode-scanner-active');

  // Add the `barcodeScanned` listener
  const listener = await BarcodeScanner.addListener(
    'barcodeScanned',
    async result => {
      console.log(result.barcode);
    },
  );

  // Start the barcode scanner
  await BarcodeScanner.startScan();
};

const stopScan = async () => {
  // Make all elements in the WebView visible again
  document.querySelector('body')?.classList.remove('barcode-scanner-active');

  // Remove all listeners
  await BarcodeScanner.removeAllListeners();

  // Stop the barcode scanner
  await BarcodeScanner.stopScan();
};

const scanSingleBarcode = async () => {
  return new Promise(async resolve => {
    document.querySelector('body')?.classList.add('barcode-scanner-active');

    const listener = await BarcodeScanner.addListener(
      'barcodeScanned',
      async result => {
        await listener.remove();
        document
          .querySelector('body')
          ?.classList.remove('barcode-scanner-active');
        await BarcodeScanner.stopScan();
        resolve(result.barcode);
      },
    );

    await BarcodeScanner.startScan();
  });
};

const scan = async () => {
  const { barcodes } = await BarcodeScanner.scan({
    formats: [BarcodeFormat.QrCode],
    lensFacing: LensFacing.Back,
  });
  return barcodes;
};

const isSupported = async () => {
  const { supported } = await BarcodeScanner.isSupported();
  return supported;
};

const enableTorch = async () => {
  await BarcodeScanner.enableTorch();
};

const disableTorch = async () => {
  await BarcodeScanner.disableTorch();
};

const toggleTorch = async () => {
  await BarcodeScanner.toggleTorch();
};

const isTorchEnabled = async () => {
  const { enabled } = await BarcodeScanner.isTorchEnabled();
  return enabled;
};

const isTorchAvailable = async () => {
  const { available } = await BarcodeScanner.isTorchAvailable();
  return available;
};

const openSettings = async () => {
  await BarcodeScanner.openSettings();
};

const isGoogleBarcodeScannerModuleAvailable = async () => {
  const { available } =
    await BarcodeScanner.isGoogleBarcodeScannerModuleAvailable();
  return available;
};

const installGoogleBarcodeScannerModule = async () => {
  await BarcodeScanner.installGoogleBarcodeScannerModule();
};

const checkPermissions = async () => {
  const { camera } = await BarcodeScanner.checkPermissions();
  return camera;
};

const requestPermissions = async () => {
  const { camera } = await BarcodeScanner.requestPermissions();
  return camera;
};

An example of the CSS class barcode-scanner-active with Ionic could be:

// Hide all elements
body.barcode-scanner-active {
  visibility: hidden;
  --background: transparent;
  --ion-background-color: transparent;
}

// Show only the barcode scanner modal
.barcode-scanner-modal {
  visibility: visible;
}

@media (prefers-color-scheme: dark) {
  .barcode-scanner-modal {
    --background: transparent;
    --ion-background-color: transparent;
  }
}

An example of the CSS class barcode-scanner-active without Ionic could be:

// Hide all elements
body.barcode-scanner-active {
  visibility: hidden;
}

// Show only the barcode scanner modal
.barcode-scanner-modal {
  visibility: visible;
}

If you can't see the camera view, make sure all elements in the DOM are not visible or have a transparent background to debug the issue.

API

startScan(...)

startScan(options?: StartScanOptions | undefined) => Promise<void>

Start scanning for barcodes.

Only available on Android and iOS.

ParamType
optionsStartScanOptions

Since: 0.0.1


stopScan()

stopScan() => Promise<void>

Stop scanning for barcodes.

Only available on Android and iOS.

Since: 0.0.1


setScanSettings(...)

setScanSettings(options?: ScanSettingOptions | undefined) => Promise<void>

Sets the scan session's settings

ParamType
optionsScanSettingOptions

readBarcodesFromImage(...)

readBarcodesFromImage(options: ReadBarcodesFromImageOptions) => Promise<ReadBarcodesFromImageResult>

Read barcodes from an image.

Only available on Android and iOS.

ParamType
optionsReadBarcodesFromImageOptions

Returns: Promise<ReadBarcodesFromImageResult>

Since: 0.0.1


scan(...)

scan(options?: ScanOptions | undefined) => Promise<ScanResult>

Scan a barcode with a ready-to-use interface without WebView customization.

On Android, this method is only available on devices with Google Play Services installed. Therefore, no camera permission is required.

Attention: Before using this method on Android, first check if the Google Barcode Scanner module is available.

Only available on Android and iOS.

ParamType
optionsScanOptions

Returns: Promise<ScanResult>

Since: 0.0.1


isSupported()

isSupported() => Promise<IsSupportedResult>

Returns whether or not the barcode scanner is supported.

Available on Android and iOS.

Returns: Promise<IsSupportedResult>

Since: 0.0.1


enableTorch()

enableTorch() => Promise<void>

Enable camera's torch (flash) during a scan session.

Only available on Android and iOS.

Since: 0.0.1


disableTorch()

disableTorch() => Promise<void>

Disable camera's torch (flash) during a scan session.

Only available on Android and iOS.

Since: 0.0.1


toggleTorch()

toggleTorch() => Promise<void>

Toggle camera's torch (flash) during a scan session.

Only available on Android and iOS.

Since: 0.0.1


isTorchEnabled()

isTorchEnabled() => Promise<IsTorchEnabledResult>

Returns whether or not the camera's torch (flash) is enabled.

Only available on Android and iOS.

Returns: Promise<IsTorchEnabledResult>

Since: 0.0.1


isTorchAvailable()

isTorchAvailable() => Promise<IsTorchAvailableResult>

Returns whether or not the camera's torch (flash) is available.

Only available on Android and iOS.

Returns: Promise<IsTorchAvailableResult>

Since: 0.0.1


openSettings()

openSettings() => Promise<void>

Open the settings of the app so that the user can grant the camera permission.

Only available on Android and iOS.

Since: 0.0.1


isGoogleBarcodeScannerModuleAvailable()

isGoogleBarcodeScannerModuleAvailable() => Promise<IsGoogleBarcodeScannerModuleAvailableResult>

Check if the Google Barcode Scanner module is available.

Only available on Android.

Returns: Promise<IsGoogleBarcodeScannerModuleAvailableResult>

Since: 5.1.0


installGoogleBarcodeScannerModule()

installGoogleBarcodeScannerModule() => Promise<void>

Install the Google Barcode Scanner module.

Attention: This only starts the installation. The googleBarcodeScannerModuleInstallProgress event listener will notify you when the installation is complete.

Only available on Android.

Since: 5.1.0


checkPermissions()

checkPermissions() => Promise<PermissionStatus>

Check camera permission.

Only available on Android and iOS.

Returns: Promise<PermissionStatus>

Since: 0.0.1


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

Request camera permission.

Only available on Android and iOS.

Returns: Promise<PermissionStatus>

Since: 0.0.1


addListener('barcodeScanned', ...)

addListener(eventName: 'barcodeScanned', listenerFunc: (event: BarcodeScannedEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Called when a barcode is scanned.

Available on Android and iOS.

ParamType
eventName'barcodeScanned'
listenerFunc(event: BarcodeScannedEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 0.0.1


addListener('scanError', ...)

addListener(eventName: 'scanError', listenerFunc: (event: ScanErrorEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Called when an error occurs during the scan.

Available on Android and iOS.

ParamType
eventName'scanError'
listenerFunc(event: ScanErrorEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 0.0.1


addListener('googleBarcodeScannerModuleInstallProgress', ...)

addListener(eventName: 'googleBarcodeScannerModuleInstallProgress', listenerFunc: (event: GoogleBarcodeScannerModuleInstallProgressEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Called when the Google Barcode Scanner module is installed.

Available on Android.

ParamType
eventName'googleBarcodeScannerModuleInstallProgress'
listenerFunc(event: GoogleBarcodeScannerModuleInstallProgressEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 5.1.0


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 0.0.1


Interfaces

StartScanOptions

PropTypeDescriptionSince
formatsBarcodeFormat[]Improve the speed of the barcode scanner by configuring the barcode formats to scan for.0.0.1
lensFacingLensFacingConfigure the camera (front or back) to use.0.0.1

ScanSettingOptions

PropType
withImageboolean
withTextboolean

ReadBarcodesFromImageResult

PropTypeDescriptionSince
barcodesBarcode[]The detected barcodes.0.0.1

Barcode

PropTypeDescriptionSince
bytesnumber[]Raw bytes as it was encoded in the barcode.0.0.1
cornerPoints[number, number, number, number, number, number, number, number]The four corner points of the barcode in clockwise order starting with top-left. This property is currently only supported by the startScan(...) method.0.0.1
displayValuestringThe barcode value in a human readable format.0.0.1
formatBarcodeFormatThe barcode format.0.0.1
rawValuestringThe barcode value in a machine readable format.0.0.1
valueTypeBarcodeValueTypeThe barcode value type.0.0.1

ReadBarcodesFromImageOptions

PropTypeDescriptionSince
formatsBarcodeFormat[]Improve the speed of the barcode scanner by configuring the barcode formats to scan for.0.0.1
pathstringThe local path to the image file.0.0.1

ScanResult

PropTypeDescriptionSince
barcodesBarcode[]The detected barcodes.0.0.1
imagestringThe base64 encoded image of the scanned barcode.

ScanOptions

PropTypeDescriptionSince
formatsBarcodeFormat[]Improve the speed of the barcode scanner by configuring the barcode formats to scan for.0.0.1

IsSupportedResult

PropTypeDescriptionSince
supportedbooleanWhether or not the barcode scanner is supported.0.0.1

IsTorchEnabledResult

PropTypeDescriptionSince
enabledbooleanWhether or not the torch is enabled.0.0.1

IsTorchAvailableResult

PropTypeDescriptionSince
availablebooleanWhether or not the torch is available.0.0.1

IsGoogleBarcodeScannerModuleAvailableResult

PropTypeDescriptionSince
availablebooleanWhether or not the Google Barcode Scanner module is available.5.1.0

PermissionStatus

PropTypeSince
cameraCameraPermissionState0.0.1

PluginListenerHandle

PropType
remove() => Promise<void>

BarcodeScannedEvent

PropTypeDescriptionSince
barcodeBarcodeA detected barcode.0.0.1
imagestring
textany

ScanErrorEvent

PropTypeDescriptionSince
messagestringThe error message.0.0.1

GoogleBarcodeScannerModuleInstallProgressEvent

PropTypeDescriptionSince
stateGoogleBarcodeScannerModuleInstallStateThe current state of the installation.5.1.0
progressnumberThe progress of the installation in percent between 0 and 100.5.1.0

Type Aliases

CameraPermissionState

PermissionState | 'limited'

PermissionState

'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'

Enums

BarcodeFormat

MembersValueDescriptionSince
Aztec'AZTEC'Only available on Android and iOS.0.0.1
Codabar'CODABAR'Only available on Android and iOS.0.0.1
Code39'CODE_39'Only available on Android and iOS.0.0.1
Code93'CODE_93'Only available on Android and iOS.0.0.1
Code128'CODE_128'Only available on Android and iOS.0.0.1
DataMatrix'DATA_MATRIX'Only available on Android and iOS.0.0.1
Ean8'EAN_8'Only available on Android and iOS.0.0.1
Ean13'EAN_13'Only available on Android and iOS.0.0.1
Itf'ITF'Only available on Android and iOS.0.0.1
Pdf417'PDF_417'Only available on Android and iOS.0.0.1
QrCode'QR_CODE'Only available on Android and iOS.0.0.1
UpcA'UPC_A'Only available on Android and iOS.0.0.1
UpcE'UPC_E'Only available on Android and iOS.0.0.1

LensFacing

MembersValueSince
Front'FRONT'0.0.1
Back'BACK'0.0.1

BarcodeValueType

MembersValueSince
CalendarEvent'CALENDAR_EVENT'0.0.1
ContactInfo'CONTACT_INFO'0.0.1
DriversLicense'DRIVERS_LICENSE'0.0.1
Email'EMAIL'0.0.1
Geo'GEO'0.0.1
Isbn'ISBN'0.0.1
Phone'PHONE'0.0.1
Product'PRODUCT'0.0.1
Sms'SMS'0.0.1
Text'TEXT'0.0.1
Url'URL'0.0.1
Wifi'WIFI'0.0.1
Unknown'UNKNOWN'0.0.1

GoogleBarcodeScannerModuleInstallState

MembersValueSince
UNKNOWN05.1.0
PENDING15.1.0
DOWNLOADING25.1.0
CANCELED35.1.0
COMPLETED45.1.0
FAILED55.1.0
INSTALLING65.1.0
DOWNLOAD_PAUSED75.1.0

Terms & Privacy

This plugin uses the Google ML Kit:

Changelog

See CHANGELOG.md.

License

See LICENSE.

^1: This project is not affiliated with, endorsed by, sponsored by, or approved by Google LLC or any of their affiliates or subsidiaries. ^2: QR Code is a registered trademark of DENSO WAVE INCORPORATED.

5.1.16

9 months ago

5.1.15

9 months ago

5.1.14

9 months ago

5.1.13

9 months ago

5.1.12

9 months ago

5.1.11

9 months ago

5.1.10

9 months ago

5.1.9

9 months ago

5.1.8

9 months ago

5.1.7

9 months ago

5.1.6

9 months ago

5.1.5

9 months ago

5.1.4

9 months ago

5.1.3

9 months ago

5.1.2

9 months ago

5.1.1

9 months ago

5.1.0

9 months ago