• Stars
    star
    435
  • Rank 100,085 (Top 2 %)
  • Language
    Java
  • License
    MIT License
  • Created about 4 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A fast and efficient (QR) barcode scanner for Capacitor


Barcode Scanner

@capacitor-community/barcode-scanner

A fast and efficient (QR) barcode scanner for Capacitor.


Table of Contents

Maintainers

Maintainer GitHub Active
thegnuu thegnuu yes
tafelnl tafelnl no

About

Supported barcodes

On iOS this library makes use of Apple's own AVFoundation. This means this list of barcodes should be supported.

On Android this library uses zxing-android-embedded which uses zxing under the hood. That means this list of barcodes is supported.

On Web this library uses zxing/browser. That means this list of barcodes is supported. The web implementation is currently in development, there might be issues and not all features are currently supported!

Note on supported Capacitor versions

v5.x.x-beta.x pre-release based on ML-Kit that supports Capacitor v5.x

v4.x supports Capacitor v5.x

v3.x supports Capacitor v4.x

v2.x supports Capacitor v3.x

v1.x supports Capacitor v2.x

All releases of this package can be found on npm and on GitHub Releases

Installation

npm install @capacitor-community/barcode-scanner
npx cap sync

iOS

For iOS you need to set a usage description in your info.plist file.

This can be done by either adding it to the Source Code directly or by using Xcode Property List inspector.

Adding it to the source code directly

  1. Open up the Info.plist (in Xcode right-click > Open As > Source Code)
  2. With <dict></dict> change the following
<dict>
+  <key>NSCameraUsageDescription</key>
+  <string>To be able to scan barcodes</string>
</dict>

NOTE: "To be able to scan barcodes" can be substituted for anything you like.

Adding it by using Xcode Property List inspector

  1. Open up the Info.plist in Xcode (right-click > Open As > Property List)
  2. Next to "Information Property List" click on the tiny + button.
  3. Under key, type "Privacy - Camera Usage Description"
  4. Under value, type "To be able to scan barcodes"

NOTE: "To be able to scan barcodes" can be substituted for anything you like.

More info here: https://developer.apple.com/documentation/bundleresources/information_property_list/nscamerausagedescription

Android

Within your AndroidManifest.xml file, change the following:

<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
+  xmlns:tools="http://schemas.android.com/tools"
  package="com.example">

  <application
+    android:hardwareAccelerated="true"
  >
  </application>

+  <uses-permission android:name="android.permission.CAMERA" />

+  <uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />
</manifest>

Usage

The complete API reference can be found here.

Scanning a (QR) barcode can be as simple as:

import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const startScan = async () => {
  // Check camera permission
  // This is just a simple example, check out the better checks below
  await BarcodeScanner.checkPermission({ force: true });

  // make background of WebView transparent
  // note: if you are using ionic this might not be enough, check below
  BarcodeScanner.hideBackground();

  const result = await BarcodeScanner.startScan(); // start scanning and wait for a result

  // if the result has content
  if (result.hasContent) {
    console.log(result.content); // log the raw scanned content
  }
};

Opacity of the WebView

hideBackground() will make the <html> element transparent by adding background: 'transparent'; to the style attribute.

If you are using Ionic you need to set some css variables as well, check here

If you still cannot see the camera view, check here

Stopping a scan

After startScan() is resolved, the Scanner View will be automatically destroyed to save battery. But if you want to cancel the scan before startScan() is resolved (AKA no code has been recognized yet), you will have to call stopScan() manually. Example:

import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const stopScan = () => {
  BarcodeScanner.showBackground();
  BarcodeScanner.stopScan();
};

It is also important to think about cases where a users hits some sort of a back button (either hardware or software). It is advised to call stopScan() in these types of situations as well.

In Vue.js you could do something like this in a specific view where you use the scanner:

<script>
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

export default {
  methods: {
    stopScan() {
      BarcodeScanner.showBackground();
      BarcodeScanner.stopScan();
    },
  },

  deactivated() {
    this.stopScan();
  },

  beforeDestroy() {
    this.stopScan();
  },
};
</script>

Preparing a scan

To boost performance and responsiveness (by just a bit), a prepare() method is available. If you know your script will call startScan() sometime very soon, you can call prepare() to make startScan() work even faster.

For example:

import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const prepare = () => {
  BarcodeScanner.prepare();
};

const startScan = async () => {
  BarcodeScanner.hideBackground();
  const result = await BarcodeScanner.startScan();
  if (result.hasContent) {
    console.log(result.content);
  }
};

const stopScan = () => {
  BarcodeScanner.showBackground();
  BarcodeScanner.stopScan();
};

const askUser = () => {
  prepare();

  const c = confirm('Do you want to scan a barcode?');

  if (c) {
    startScan();
  } else {
    stopScan();
  }
};

askUser();

This is fully optional and would work the same as:

import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const startScan = async () => {
  BarcodeScanner.hideBackground();
  const result = await BarcodeScanner.startScan();
  if (result.hasContent) {
    console.log(result.content);
  }
};

const askUser = () => {
  const c = confirm('Do you want to scan a barcode?');

  if (c) {
    startScan();
  }
};

askUser();

The latter will just appear a little slower to the user.

Permissions

This plugin does not automatically handle permissions. But the plugin does have a utility method to check and request the permission. You will have to request the permission from JavaScript. A simple example follows:

import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const checkPermission = async () => {
  // check or request permission
  const status = await BarcodeScanner.checkPermission({ force: true });

  if (status.granted) {
    // the user granted permission
    return true;
  }

  return false;
};

A more detailed and more UX-optimized example:

import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const didUserGrantPermission = async () => {
  // check if user already granted permission
  const status = await BarcodeScanner.checkPermission({ force: false });

  if (status.granted) {
    // user granted permission
    return true;
  }

  if (status.denied) {
    // user denied permission
    return false;
  }

  if (status.asked) {
    // system requested the user for permission during this call
    // only possible when force set to true
  }

  if (status.neverAsked) {
    // user has not been requested this permission before
    // it is advised to show the user some sort of prompt
    // this way you will not waste your only chance to ask for the permission
    const c = confirm('We need your permission to use your camera to be able to scan barcodes');
    if (!c) {
      return false;
    }
  }

  if (status.restricted || status.unknown) {
    // ios only
    // probably means the permission has been denied
    return false;
  }

  // user has not denied permission
  // but the user also has not yet granted the permission
  // so request it
  const statusRequest = await BarcodeScanner.checkPermission({ force: true });

  if (statusRequest.asked) {
    // system requested the user for permission during this call
    // only possible when force set to true
  }

  if (statusRequest.granted) {
    // the user did grant the permission now
    return true;
  }

  // user did not grant the permission, so he must have declined the request
  return false;
};

didUserGrantPermission();

If a user denied the permission for good, status.denied will be set to true. On Android this will happen only when the user checks the box never ask again. To get the permission anyway you will have to redirect the user to the settings of the app. This can be done simply be doing the following:

import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const checkPermission = async () => {
  const status = await BarcodeScanner.checkPermission();

  if (status.denied) {
    // the user denied permission for good
    // redirect user to app settings if they want to grant it anyway
    const c = confirm('If you want to grant permission for using your camera, enable it in the app settings.');
    if (c) {
      BarcodeScanner.openAppSettings();
    }
  }
};

Target only specific barcodes

You can setup the scanner to only recognize specific types of barcodes like this:

import { BarcodeScanner, SupportedFormat } from '@capacitor-community/barcode-scanner';

BarcodeScanner.startScan({ targetedFormats: [SupportedFormat.QR_CODE] }); // this will now only target QR-codes

If targetedFormats is not specified or left empty, all types of barcodes will be targeted.

Targeting only specific types can have the following benefits:

  • Improved performance (since the decoder only has to look for the specified barcodes)
  • Improved User Experience (since scanning a barcode that is not supported by your case, will not work)

The following types are supported:

Category Type Android iOS
1D Product
UPC_A ✔**
UPC_E
UPC_EAN_EXTENSION
EAN_8
EAN_13
1D Industrial
CODE_39
CODE_39_MOD_43
CODE_93
CODE_128
CODABAR
ITF
ITF_14
2D
AZTEC
DATA_MATRIX
MAXICODE
PDF_417
QR_CODE
RSS_14
RSS_EXPANDED

** UPC_A is supported on iOS, but according to the offical Apple docs it is part of EAN_13. So you should specify EAN_13 to be able to scan this. If you want to distinguish them from one another, you should manually do so after getting the result.

Troubleshooting

Ionic CSS variables

Ionic will add additional CSS variables which will prevent the scanner from showing up. To fix this issue add the following snippet at the end of your global css.

body.scanner-active {
  --background: transparent;
  --ion-background-color: transparent;
}

Once this is done, you need to add this class to the body before using the scanner.

document.querySelector('body').classList.add('scanner-active');

After your done with your scanning work, you can simply remove this class.

document.querySelector('body').classList.remove('scanner-active');

I have a Error: Plugin BarcodeScanner does not respond to method call error message on iOS

In Xcode click on Product > Clean Build Folder and try to build again.

I have a Cannot resolve symbol BarcodeScanner error message in Android Studio

In Android Studio click File > Sync Project with Gradle Files and try to build again.

The scanner view does not show up

If you cannot see the scanner in your viewport, please follow these steps:

  1. Check if camera permissions are granted properly
  2. Check if the scanner element does appear inside the DOM, somewhere within the body tag
  3. Check if some DOM elements are rendered on top of the scanner
    • Search which element is causing the issue #7
    • Play with javascript #26

I do not find the scanner in the DOM

This should appear in the DOM when running the BarcodeScanner.startScan() method.

<body>
  <!-- ... -->
  <div style="position: absolute; left: 0px; top: -2px; height: 1px; overflow: hidden; visibility: hidden; width: 1px;">
    <span
      style="position: absolute; font-size: 300px; width: auto; height: auto; margin: 0px; padding: 0px; font-family: Roboto, Arial, sans-serif;"
      >BESbswy</span
    >
  </div>
  <!-- ... -->
</body>

If it does not, it may be a bug due to the component being loaded to deep inside the DOM tree. You can try to see if the plugin is working properly by adding the following in your app.component.ts file.

BarcodeScanner.hideBackground();
const result = await BarcodeScanner.startScan();

It doesn't appear

It could mean that you have missed a step by the plugin configuration.

I did the configuration correctly

please open an issue

TODO

A non-exhaustive list of todos:

  • Support for switching between cameras
  • Support for web

More Repositories

1

sqlite

Community plugin for native & electron SQLite databases
Swift
463
star
2

electron

Deploy your Capacitor apps to Linux, Mac, and Windows desktops, with the Electron platform! 🖥️
TypeScript
327
star
3

bluetooth-le

Capacitor plugin for Bluetooth Low Energy
TypeScript
277
star
4

react-hooks

⚡️ React hooks for Capacitor ⚡️
TypeScript
244
star
5

fcm

Enable Firebase Cloud Messaging for Capacitor apps
TypeScript
240
star
6

generic-oauth2

Generic Capacitor OAuth 2 client plugin. Stop the war in Ukraine!
Java
232
star
7

admob

Community plugin for using Google AdMob
Java
209
star
8

http

Community plugin for native HTTP
Java
209
star
9

camera-preview

Capacitor plugin that allows camera interaction from HTML code
Java
188
star
10

stripe

Stripe Mobile SDK wrapper for Capacitor
Java
188
star
11

background-geolocation

A Capacitor plugin that sends you geolocation updates, even while the app is in the background.
Java
187
star
12

google-maps

Capacitor Plugin using native Google Maps SDK for Android and iOS.
Java
152
star
13

in-app-review

Let users rate your app using native review app dialog for both Android and iOS.
TypeScript
144
star
14

apple-sign-in

Sign in with Apple Support
Swift
137
star
15

vue-cli-plugin-capacitor

A Vue CLI 3/4 Plugin for Capacitor
JavaScript
131
star
16

keep-awake

⚡️ Capacitor plugin to prevent devices from dimming or locking the screen.
Java
125
star
17

firebase-analytics

Enable Firebase Analytics for Capacitor Apps
Java
122
star
18

contacts

Contacts Plugin for Capacitor
Java
114
star
19

tauri

Deploy your Capacitor apps to Linux, Mac, and Windows desktops, with the Tauri platform! 🖥️
TypeScript
108
star
20

native-audio

Java
104
star
21

facebook-login

Facebook Login support
Java
101
star
22

media

Capacitor plugin for saving and retrieving photos and videos, and managing photo albums.
TypeScript
100
star
23

text-to-speech

⚡️ Capacitor plugin for synthesizing speech from text.
Java
93
star
24

speech-recognition

Java
84
star
25

date-picker

Native DateTime Picker Plugin for Capacitor Apps
Swift
84
star
26

privacy-screen

⚡️ Capacitor plugin that protects your app from displaying a screenshot in Recents screen/App Switcher.
Swift
77
star
27

proposals

Plugin and platform requests ✋
74
star
28

app-icon

Capacitor plugin to programmatically change the app icon.
Java
74
star
29

firebase-crashlytics

⚡️ Capacitor plugin for Firebase Crashlytics.
Java
70
star
30

file-opener

Capacitor File Opener. The plugin is able to open a file given the mimeType and the file uri. This plugin is similar to cordova-plugin-file-opener2 without installation support.
Swift
64
star
31

intercom

Enable Intercom for Capacitor apps
TypeScript
57
star
32

photoviewer

PhotoViewer table images with fullscreen and sharing capabilities
Swift
49
star
33

examples

Examples of using Capacitor with popular web frameworks and libraries
JavaScript
46
star
34

safe-area

Capacitor Plugin that exposes the safe area insets from the native iOS/Android device to your web project.
Kotlin
46
star
35

welcome

Introduction to the Capacitor Community org 👋
37
star
36

appcenter-sdk-capacitor

Capacitor Plugin for Microsoft's Visual Studio App Center SDK.
TypeScript
35
star
37

in-app-purchases

WIP: In App Purchases plugin for Capacitor
Java
27
star
38

native-market

Java
26
star
39

realm

Java
25
star
40

firebase-remote-config

TypeScript
23
star
41

screen-brightness

Java
23
star
42

.github

Template repo for new community plugins
17
star
43

twitter

Capacitor plugin to enable TwitterKit
TypeScript
11
star
44

card-scanner

Simple card scanner for Capacitor Applications.
Swift
11
star
45

flipper

Java
10
star
46

auth0

TypeScript
9
star
47

volume-buttons

Capacitor Volume Buttons. The plugin enables to listen to hardware volume button presses. This plugin is based on https://github.com/thiagobrez/capacitor-volume-buttons
Swift
7
star
48

google-maps-examples

Vue
5
star
49

uxcam

UXCam and FullStory app analytics
Java
5
star
50

advertising-id

Allows access to the IDFA (iOS) and AAID (Android)
Swift
5
star
51

android-security-provider

Capacitor plugin with method to check and update the Android Security Provider.
Java
3
star
52

tap-jacking

Capacitor plugin to prevent tap jacking on Android devices
Java
2
star
53

mdm-appconfig

Capacitor community plugin for reading app configurations written by a MDM (see appconfig.org) such as VMWare Workspace One.
Java
2
star
54

exif

This plugin offers utility functions for interacting with image exif metadata
Swift
2
star
55

play-integrity

A Capacitor plugin to use the Play Integrity API
Java
1
star
56

device-check

A Capacitor plugin to use Apple's DeviceCheck API
Java
1
star