• Stars
    star
    292
  • Rank 142,152 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

🔎 NativeScript QR / barcode (bulk)scanner plugin

NativeScript BarcodeScanner

Build Status NPM version Downloads Twitter Follow

💡 Plugin version 4.0.0+ is compatible with NativeScript 7+. If you need to target older NativeScript versions, please stick to plugin version 3.4.2.

⚠️ With 4.1.0+ you can use beepOnScan on iOS again (it used to crash in older 4.x versions).

Want a quick demo?

Note that running this only makes sense on a real device.

git clone https://github.com/EddyVerbruggen/nativescript-barcodescanner barcodedemo
cd barcodedemo/src

Fullscreen, programmatically (iOS and Android)

npm run demo.android (or demo.ios / demo.ios.device)

Embedded (iOS only)

npm run demo.ios

Supported barcode types

iOS and Android

  • CODE_39
  • CODE_93
  • CODE_128
  • DATA_MATRIX
  • EAN_8
  • EAN_13
  • ITF (also known as ITF14)
  • PDF_417 (on Android only when passed in explicity via formats)
  • QR_CODE
  • UPC_A
  • UPC_E

Android only

  • CODABAR
  • MAXICODE
  • RSS_14

iOS only

  • AZTEC
  • CODE_39_MOD_43
  • INTERLEAVED_2_OF_5

A note about UPC_A and EAN_13

When either (or both) of these are specified, both can be returned. You can check the actual type by inspecting the format property of the result object. For details, see #176.

Installation

From the command prompt go to your app's root folder and execute:

tns plugin add nativescript-barcodescanner

Embedding the scanner (iOS)

If you need to embed the scanner for Android as well, please consider using the Machine Learning powered Barcode scanner I've added to the ML Kit feature of the NativeScript Firebase plugin!

As you can see, you can style the view any way you like, and even overlay it with an image or button. To recreate the layout above, look at these lines in the demo app.

💡 TIP: If you don't destroy the component/page which embed the scanner (but instead show a modal, or navigate "forward") you can "pause" the scanner (since plugin version 3.4.0). Simply set that pause property to true when applicable.

XML

<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:Barcode="nativescript-barcodescanner">

Here's an example tag, showing all currently supported options. The property defaults are equal to the scan function.

<iOS>
    <Barcode:BarcodeScannerView
      class="scanner-round"
      formats="QR_CODE, EAN_13"
      beepOnScan="true"
      reportDuplicates="true"
      preferFrontCamera="false"
      pause="{{ pause }}"
      scanResult="{{ onScanResult }}" />
</iOS>

Embedding in Angular

Component / Module:

import { registerElement } from "nativescript-angular/element-registry";
registerElement("BarcodeScanner", () => require("nativescript-barcodescanner").BarcodeScannerView);

View:

<BarcodeScanner
      class="scanner-round"
      formats="QR_CODE, EAN_13"
      beepOnScan="true"
      reportDuplicates="true"
      preferFrontCamera="false"
      [pause]="pause"
      (scanResult)="onScanResult($event)">
</BarcodeScanner>

Embedding in Vue

main.ts:

Vue.registerElement('BarcodeScanner', () => require('nativescript-barcodescanner').BarcodeScannerView)

View:

<BarcodeScanner
    row="1"
    height="300"
    formats="QR_CODE, EAN_13, UPC_A"
    beepOnScan="true"
    reportDuplicates="true"
    preferFrontCamera="false"
    :pause="pause"
    @scanResult="onScanResult"
    v-if="isIOS">
</BarcodeScanner>

See 'demo-vue' for details.

iOS runtime permission reason

You've probably seen a permission popup like this before (this plugin will trigger one as well, automatically):

iOS 10+ requires not only this popup, but also a reason. In this case it's "We'd like to use the Camera ..".

You can provide your own reason for accessing the camera by adding something like this to app/App_Resources/ios/Info.plist:

  <key>NSCameraUsageDescription</key>
  <string>My reason justifying fooling around with your camera</string>

To not crash your app in case you forgot to provide the reason this plugin adds an empty reason to the .plist during build. This value gets overridden by anything you specify yourself.

Usage

Tip: during a scan you can use the volume up/down buttons to toggle the torch.

function: scan (single mode)

TypeScript

  import { BarcodeScanner } from "nativescript-barcodescanner";
  let barcodescanner = new BarcodeScanner();

  barcodescanner.scan({
    formats: "QR_CODE, EAN_13",
    cancelLabel: "EXIT. Also, try the volume buttons!", // iOS only, default 'Close'
    cancelLabelBackgroundColor: "#333333", // iOS only, default '#000000' (black)
    message: "Use the volume buttons for extra light", // Android only, default is 'Place a barcode inside the viewfinder rectangle to scan it.'
    showFlipCameraButton: true,   // default false
    preferFrontCamera: false,     // default false
    showTorchButton: true,        // default false
    beepOnScan: true,             // Play or Suppress beep on scan (default true)
    fullScreen: true,             // Currently only used on iOS; with iOS 13 modals are no longer shown fullScreen by default, which may be actually preferred. But to use the old fullScreen appearance, set this to 'true'. Default 'false'.
    torchOn: false,               // launch with the flashlight on (default false)
    closeCallback: () => { console.log("Scanner closed")}, // invoked when the scanner was closed (success or abort)
    resultDisplayDuration: 500,   // Android only, default 1500 (ms), set to 0 to disable echoing the scanned text
    orientation: orientation,     // Android only, default undefined (sensor-driven orientation), other options: portrait|landscape
    openSettingsIfPermissionWasPreviouslyDenied: true, // On iOS you can send the user to the settings app if access was previously denied
    presentInRootViewController: true // iOS-only; If you're sure you're not presenting the (non embedded) scanner in a modal, or are experiencing issues with fi. the navigationbar, set this to 'true' and see if it works better for your app (default false).
  }).then((result) => {
      // Note that this Promise is never invoked when a 'continuousScanCallback' function is provided
      alert({
        title: "Scan result",
        message: "Format: " + result.format + ",\nValue: " + result.text,
        okButtonText: "OK"
      });
    }, (errorMessage) => {
      console.log("No scan. " + errorMessage);
    }
  );

Note that result.format above is one of these.

JavaScript

  var BarcodeScanner = require("nativescript-barcodescanner").BarcodeScanner;
  var barcodescanner = new BarcodeScanner();

  barcodescanner.scan({
    formats: "QR_CODE,PDF_417",   // Pass in of you want to restrict scanning to certain types
    cancelLabel: "EXIT. Also, try the volume buttons!", // iOS only, default 'Close'
    cancelLabelBackgroundColor: "#333333", // iOS only, default '#000000' (black)
    message: "Use the volume buttons for extra light", // Android only, default is 'Place a barcode inside the viewfinder rectangle to scan it.'
    showFlipCameraButton: true,   // default false
    preferFrontCamera: false,     // default false
    showTorchButton: true,        // default false
    beepOnScan: true,             // Play or Suppress beep on scan (default true)
    fullScreen: true,             // Currently only used on iOS; with iOS 13 modals are no longer shown fullScreen by default, which may be actually preferred. But to use the old fullScreen appearance, set this to 'true'. Default 'false'.
    torchOn: false,               // launch with the flashlight on (default false)
    closeCallback: function () { console.log("Scanner closed"); }, // invoked when the scanner was closed (success or abort)
    resultDisplayDuration: 500,   // Android only, default 1500 (ms), set to 0 to disable echoing the scanned text
    orientation: "landscape",     // Android only, optionally lock the orientation to either "portrait" or "landscape"
    openSettingsIfPermissionWasPreviouslyDenied: true // On iOS you can send the user to the settings app if access was previously denied
  }).then(
      function(result) {
        console.log("Scan format: " + result.format);
        console.log("Scan text:   " + result.text);
      },
      function(error) {
        console.log("No scan: " + error);
      }
  );

function: scan (bulk / continuous mode)

In this mode the scanner will continuously report scanned codes back to your code, but it will only be dismissed if the user tells it to, or you call stop programmatically.

The plugin handles duplicates for you so don't worry about checking those; every result withing the same scan session is unique unless you set reportDuplicates to true.

Here's an example of scanning 3 unique QR codes and then stopping scanning programmatically. You'll notice that the Promise will no longer receive the result as there may be many results:

JavaScript

  var count = 0;
  barcodescanner.scan({
    formats: "QR_CODE",
    // this callback will be invoked for every unique scan in realtime!
    continuousScanCallback: function (result) {
      count++;
      console.log(result.format + ": " + result.text + " (count: " + count + ")");
      if (count === 3) {
        barcodescanner.stop();
      }
    },
    closeCallback: function () { console.log("Scanner closed"); }, // invoked when the scanner was closed
    reportDuplicates: false // which is the default
  }).then(
      function() {
        console.log("We're now reporting scan results in 'continuousScanCallback'");
      },
      function(error) {
        console.log("No scan: " + error);
      }
  );

function: available

Note that the iOS implementation will always return true at the moment, on Android we actually check for a camera to be available.

JavaScript

  var barcodescanner = require("nativescript-barcodescanner");

  barcodescanner.available().then(
      function(avail) {
        console.log("Available? " + avail);
      }
  );

function: hasCameraPermission / requestCameraPermission

On Android 6+ you need to request permission to use the camera at runtime when targeting API level 23+. Even if the uses-permission tag for the Camera is present in AndroidManifest.xml.

On iOS 10+ there's something similar going on.

Since version 1.5.0 you can let the plugin handle this for you (if need be a prompt will be shown to the user when the scanner launches), but if for some reason you want to handle permissions yourself you can use these functions.

JavaScript

  barcodescanner.hasCameraPermission().then(
      function(granted) {
        // if this is 'false' you probably want to call 'requestCameraPermission' now
        console.log("Has Camera Permission? " + result);
      }
  );

  // if no permission was granted previously this wil open a user consent screen
  barcodescanner.requestCameraPermission().then(
      function() {
        console.log("Camera permission requested");
      }
  );

Usage with nativescript-angular

You may have injected the BarcodeScanner class in your component constructor in the past, but please don't do that anymore because in release builds you may experience a crash.

So instead of:

// my-component.ts
import { Component, Inject } from '@angular/core';
import { BarcodeScanner } from 'nativescript-barcodescanner';

@Component({ ... })
  export class MyComponent {
    constructor(private barcodeScanner: BarcodeScanner) {
  }

  //use the barcodescanner wherever you need it. See general usage above.
  scanBarcode() {
    this.barcodeScanner.scan({ ... });
  }
}

Simply do:

// my-component.ts
import { Component, Inject } from '@angular/core';
import { BarcodeScanner } from 'nativescript-barcodescanner';

@Component({ ... })
  //use the barcodescanner wherever you need it. See general usage above.
  scanBarcode() {
    new BarcodeScanner().scan({ ... });
  }
}

Webpack usage

If you run into an error when Webpacking, open app.module.ts and add this:

import { BarcodeScanner } from "nativescript-barcodescanner";

export function createBarcodeScanner() {
  return new BarcodeScanner();
}

providers: [
  { provide: BarcodeScanner, useFactory: (createBarcodeScanner) }
]

Troubleshooting

If you get the error TypeError: Cannot read property 'zxing' of undefined on android, try the following steps:

  1. Delete the app from your device
  2. Remove the folder platforms/android. This triggers a complete rebuild
  3. run tns run android

Dependencies / Related Projects

This plugin wraps libaries for Android and iOS to make the barcode scanner easily accessible via a unified API. The Libraries used are:

iOS

Custom Framework to access iOS APIs: https://github.com/EddyVerbruggen/ios-framework-barcodescanner

Android

ZXing: https://github.com/zxing/zxing/releases

As using that library as a direct dependency was not practical, there is a library-project that adopts the sources from ZXing and copiles them into a AAR for usage on android: https://github.com/EddyVerbruggen/barcodescanner-lib-aar/

More Repositories

1

SocialSharing-PhoneGap-Plugin

👨‍❤️‍💋‍👨 Cordova plugin to share text, a file (image/PDF/..), or a URL (or all three) via the native sharing widget
Objective-C
1,778
star
2

nativescript-plugin-firebase

🔥 NativeScript plugin for Firebase
TypeScript
1,011
star
3

Calendar-PhoneGap-Plugin

📅 Cordova plugin to Create, Change, Delete and Find Events in the native Calendar
Java
773
star
4

cordova-plugin-googleplus

➕ Cordova plugin to login with Google Sign-In on iOS and Android
Java
567
star
5

Toast-PhoneGap-Plugin

🍻 A Toast popup plugin for your fancy Cordova app
C++
509
star
6

cordova-plugin-safariviewcontroller

🐯 🐘 🐊 Forget InAppBrowser for iOS - this is way better for displaying read-only web content in your PhoneGap app
Java
281
star
7

cordova-plugin-native-keyboard

🎹 Add a Slack / WhatsApp - style chat keyboard to your Cordova app!
Objective-C
275
star
8

Insomnia-PhoneGap-Plugin

😪 Prevent the screen of the mobile device from falling asleep
JavaScript
266
star
9

cordova-plugin-touch-id

💅 👱‍♂️ Forget passwords, use a fingerprint scanner!
Objective-C
216
star
10

cordova-plugin-actionsheet

📋 ActionSheet plugin for Cordova iOS and Android apps
JavaScript
208
star
11

cordova-plugin-3dtouch

👇 Quick Home Icon Actions and Link Previews
Objective-C
176
star
12

nativescript-pluginshowcase

An app I'm using to showcase a bunch of NativeScript plugins (also in the appstores!)
TypeScript
175
star
13

HealthKit

Cordova plugin for the iOS HealthKit framework
Objective-C
168
star
14

remove.bg

A Node.js wrapper for the remove.bg API
TypeScript
162
star
15

nativescript-local-notifications

📫 NativeScript plugin to easily schedule local notifications
TypeScript
162
star
16

SSLCertificateChecker-PhoneGap-Plugin

🛂 Prevent Man in the Middle attacks with this Cordova plugin
Objective-C
156
star
17

VideoCapturePlus-PhoneGap-Plugin

🎥
Objective-C
133
star
18

nativescript-fingerprint-auth

💅 👱‍♂️ Forget passwords, use a fingerprint scanner or facial recognition!
TypeScript
133
star
19

nativescript-feedback

📢 Non-blocking textual feedback for your NativeScript app
TypeScript
129
star
20

nativescript-ar

Augmented Reality NativeScript plugin
TypeScript
118
star
21

nativescript-secure-storage

🔐 NativeScript plugin for secure local storage of fi. passwords
TypeScript
108
star
22

nativescript-nodeify

Makes most npm packages compatible with NativeScript
JavaScript
91
star
23

nativescript-speech-recognition

💬 Speech to text, using the awesome engines readily available on the device.
TypeScript
90
star
24

nativescript-directions

👆 👉 👇 👈 Open the Maps app to show directions to anywhere you like
TypeScript
81
star
25

nativescript-localize

Internationalization plugin for NativeScript using native capabilities of each platform
TypeScript
79
star
26

nativescript-nfc

📝 NativeScript plugin to discover, read, and write NFC tags
TypeScript
77
star
27

nativescript-keyboard-toolbar

⌨️🛠Add a customizable toolbar on top of the soft keyboard
TypeScript
69
star
28

nativescript-admob

NativeScript plugin to earn some precious 💰💰 with ads by Google AdMob
JavaScript
68
star
29

cordova-plugin-ios-longpress-fix

🔍 Suppress the magnifying glass when long pressing an iOS9 PhoneGap app
Objective-C
67
star
30

nativescript-i18n

This is a plugin for Nativescript that implements native i18n in an easy manner.
JavaScript
65
star
31

cordova-plugin-taptic-engine

📳 Use Apple's Taptic Engine to vibrate your iPhone 6s (or up) in a variety of ways
Objective-C
61
star
32

Flashlight-PhoneGap-Plugin

🔦 Cordova plugin for using the torch / flashlight of your device
Java
60
star
33

cordova-plugin-backgroundaudio

🎶 Background Audio plugin for Cordova PhoneGap apps
Objective-C
57
star
34

nativescript-gradient

🎨 Easily add fancy (or subtle) gradient backgrounds to your views
TypeScript
54
star
35

nativescript-app-shortcuts

👇 Home Icon Actions for your NativeScript app, now also for Android!
TypeScript
48
star
36

nativescript-appversion

🔢 NativeScript plugin to retrieve your app's package ID and current version
JavaScript
48
star
37

nativescript-email

✉️ NativeScript plugin for opening draft e-mails
JavaScript
47
star
38

nativescript-calendar

📅 NativeScript plugin to Create, Delete and Find Events in the native Calendar
TypeScript
44
star
39

barcodescanner-lib-aar

Project which compiles barcodescanner sources to an aar for use in Android projects
Java
41
star
40

nativescript-clipboard

📋 NativeScript plugin to copy stuff to the device clipboard, and read from it again
TypeScript
40
star
41

nativescript-apple-sign-in

Sign In With Apple, as seen on WWDC 2019, available with iOS 13
TypeScript
39
star
42

footplr

An app using NativeScript and Vue with Firebase (Firestore)
HTML
38
star
43

nativescript-ocr

📰 🔍 Tesseract-powered OCR plugin for NativeScript
TypeScript
38
star
44

nativescript-printer

📠 Send an image or the screen contents to a physical printer
TypeScript
35
star
45

HeadsetDetection-PhoneGap-Plugin

🎧 A PhoneGap plugin for detection of a headset (wired or bluetooth)
Java
34
star
46

nativescript-numeric-keyboard

🔢 Replace the meh default number/phone keyboard with this stylish one
TypeScript
33
star
47

nativescript-keyframes

Facebook Keyframes plugin - if CSS animations don't cut it for ya
JavaScript
32
star
48

nativescript-star-printer

🌟 Print directly to Star Micronics printers from your NativeScript app! http://www.starmicronics.com/
Objective-C
32
star
49

cordova-plugin-app-icon-changer

Change the homescreen icon of your Cordova iOS app at runtime!
Objective-C
32
star
50

nativescript-bluetooth-demo

JavaScript
30
star
51

nativescript-android-tv

A little PoC demonstrating code sharing between Android Phone and TV apps
TypeScript
27
star
52

nativescript-homekit

🏡 HomeKit plugin for your fancy NativeScript app
TypeScript
24
star
53

nativescript-plugin-firebase-demo

Demo app for the NativeScript Firebase plugin
JavaScript
24
star
54

nativescript-performance-monitor

⚡ Proof your app maintains 60-ish FPS by collecting data or showing it on screen with this NativeScript plugin!
TypeScript
21
star
55

nativescript-pushy

Easy push notifications for your NativeScript app!
TypeScript
21
star
56

nativescript-webview-utils

🕸Add request headers to a NativeScript WebView. Perhaps more utils later.
TypeScript
20
star
57

nativescript-particle

🕹 Control your https://particle.io devices from NativeScript
TypeScript
20
star
58

cordova-plugin-webviewcolor

Objective-C
19
star
59

nativescript-appavailability

🔎 NativeScript plugin to check whether or not another app is installed on the device
JavaScript
19
star
60

nativescript-mapbox-demo

Demo app for the NativeScript Mapbox plugin
JavaScript
18
star
61

nativescript-pedometer

🐾 step count tracking plugin for your NativeScript app
TypeScript
17
star
62

nativescript-taptic-engine

📳 Use Apple's Taptic Engine to vibrate your iPhone 6s (and up) in a variety of ways
Vue
16
star
63

nativescript-app-icon-changer

Change the homescreen icon of your NativeScript iOS app at runtime!
TypeScript
16
star
64

nativescript-local-notifications-demo

Demo app for the NativeScript local notifications plugin
JavaScript
15
star
65

nativescript-dark-mode

NativeScript plugin to tap into iOS13's Dark Mode and Android's Night Mode configs
TypeScript
15
star
66

nativescript-aws

[DEPRECATED, see the readme] NativeScript plugin for Amazon's AWS ☁️ services
JavaScript
15
star
67

nativescript-headset-detection

Detect when a headphone (jack or bluetooth) is (dis)connected.
TypeScript
14
star
68

CameraRoll-PhoneGap-Plugin

Objective-C
11
star
69

nativescripthighcharts

Demoing how to add highcharts to your NativeScript app
TypeScript
10
star
70

NativePageTransitions-Ionic-Demo

Demo App for Ionic framwork apps with the Native Page Transitions plugin
JavaScript
10
star
71

X-Services-PhoneGap-Build-Plugins-Demo

A demo repo for all of our PhoneGap Build plugins
JavaScript
10
star
72

nativescript-call

NativeScript plugin to interact with the native Call UI
TypeScript
8
star
73

cordova-plugin-researchkit

Cordova / PhoneGap plugin for the Apple's ResearchKit
Objective-C
8
star
74

phonegapbuildmonitor

Repository for the iOS and Android PhoneGap Build app: Buildmeister
CSS
6
star
75

nativescript-izettle

Accept payments directly in your NativeScript app with iZettle
5
star
76

nativescript-calendar-demo

Demo app for the NativeScript Calendar plugin
JavaScript
5
star
77

ns-vue-firebase-test

Sample code to show how to use Firebase with the NS-Vue Vue CLI template
JavaScript
5
star
78

nativescript-randombytes

🔀 🔢 A NativeScript shim for the randombytes package
JavaScript
4
star
79

nativescript-date-utils

A simple plugin with a few date-related utilities
Shell
4
star
80

nativescript-admob-demo

Demo app for the NativeScript AdMob plugin
JavaScript
4
star
81

nativescript-snapkit

Log in to your app with your Snapchat account
TypeScript
3
star
82

ios-framework-barcodescanner

An iOS BarcodeScanner .framework library, wrapping the built-in iOS barcodescanner capabilities
Objective-C
2
star
83

bridgematebroadcast

Java
2
star
84

nativescript-barcodescanner-demo

Demo app for the NativeScript BarcodeScanner plugin
JavaScript
2
star
85

nativescript-ios-out-of-memory

Reproducing NativeScript issue 4490
JavaScript
1
star
86

nativescript-wkwebview

NativeScript WKWebView plugin for iOS
JavaScript
1
star
87

iOSMinVersion-PhoneGapBuild-Plugin

A PhoneGap Build plugin for overriding the minimal iOS version to deploy your app on.
1
star
88

iPadLandscapeEnabler-PhoneGapBuild-Plugin

1
star
89

mgggplus-frontend

Mobile client
JavaScript
1
star
90

nativescript-socket-mobile

1
star
91

Karma-App

JavaScript
1
star
92

nativescript-mapbox-vision

This is just a test, please ignore this repo for now 😊
TypeScript
1
star
93

cordova-and-nativescript-pokemon-app

Showing how to create a similar app in both Cordova and NativeScript, using plugins for SocialSharing and NetworkInformation.
TypeScript
1
star