Implement A Barcode Scanner Using Ionic Framework

I recently found myself needing to scan barcodes in one of my apps.  More specifically I needed to scan quick response (QR) codes.  After doing some searching I found that ngCordova had an extension for the Apache Cordova plugin BarcodeScanner which has the ability to scan barcodes in the following formats:

  • QR Code
  • Data Matrix
  • UPC E
  • UPC A
  • EAN 8
  • EAN 13
  • Code 128
  • Code 39
  • ITF

Pretty much all the formats anyone would ever need.  The plugin itself makes use of the very popular ZXing library.

To implement the barcode scanner in our Android and iOS application, lets start by creating a new Ionic Framework project.

Remember, if you’re not using a Mac, you cannot add and build for the iOS platform.

The next thing we want to do is add the barcode scanner plugin into our project.  This can be done by doing the following from a command line:

Now technically you can continue to build your application with just the plugin, but we are going to install the AngularJS ngCordova extension set to make our lives a little easier.

Start by downloading the latest ngCordova release and copying the ng-cordova.min.js file into your project’s www/js directory.

To add the extension set into our application we must first include the script before the cordova.js line in our index.html file.  It will look something like this:

With your index.html file set up, now we need to add the extension set to our app.js file.  Alter your angular.module line to look something like the following:

It is now time to work some programming magic.  Create a controller and include the following method to initialize the barcode scanner.  For this example, I did the following:

You’ll notice that we had to include $cordovaBarcodeScanner in our controller.  The scanner returns an AngularJS promise, so if there is an error or success we’ll know about it.

Just like that, you’ve got a very simple barcode scanner in your Ionic Framework application.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Aman

    Hi,
    I followed the exact steps but I get the following error
    Error: [$injector:unpr] Unknown provider: $corodvaBarcodeScannerProvider <- $corodvaBarcodeScanner
    http://errors.angularjs.org/1.2.25/$injector/unpr?p0=%24corodvaBarcodeScannerProvider%20%3C-%20%24corodvaBarcodeScanner
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:7703:12
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:11427:19

    Can you please help.

    • Hi Aman,

      Are you trying to test from your browser? Although ngCordova is an extension for AngularJS, the barcode scanner itself uses native code which cannot be tested from a browser.

      Please let me know if this was the issue.

      Cheers,

      • Aman

        Yes, I was testing from Chrome, however I also tried testing using Genymotion.

        • Hi Aman,

          What error do you get in Genymotion when you use adb logcat?

          Regards,

    • Brian Saville

      Older post, but I was looking through and noticed you misspelled “cordova” as “corodva”. Try it with $cordovaBarcodeScanner instead of $corodvaBarcodeScanner.

      • Good catch! Typos are terrible to track down.

  • Aman

    Similar to one I see in chrome – unknown provider

    I/ActivityManager( 539): Displayed com.ionicframework.barcodetest779129/.barcodetest: +252ms
    D/CordovaWebViewClient( 1449): onPageStarted(file:///android_asset/www/index.html)
    D/CordovaActivity( 1449): onMessage(onPageStarted,file:///android_asset/www/index.html)
    D/JsMessageQueue( 1449): Set native->JS mode to OnlineEventsBridgeMode
    D/CordovaLog( 1449): file:///android_asset/www/lib/ionic/js/ionic.bundle.js: Line 17696 : Error: [$injector:unpr] Unknow
    n provider: $corodvaBarcodeScannerProvider <- $corodvaBarcodeScanner
    D/CordovaLog( 1449): http://errors.angularjs.org/1.2.25/$injector/unpr?p0=%24corodvaBarcodeScannerProvider%20%3C-%20%24c
    orodvaBarcodeScanner
    D/CordovaLog( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:7703:12
    D/CordovaLog( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11427:19
    D/CordovaLog( 1449): at Object.getService [as get] (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11555:39)

    D/CordovaLog( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11432:45
    D/CordovaLog( 1449): at getService (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11555:39)
    D/CordovaLog( 1449): at invoke (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11582:13)
    D/CordovaLog( 1449): at Object.instantiate (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11602:23)
    D/CordovaLog( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:14906:28
    D/CordovaLog( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:14295:34
    D/CordovaLog( 1449): at forEach (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:7957:20)
    I/chromium( 1449): [INFO:CONSOLE(17696)] "Error: [$injector:unpr] Unknown provider: $corodvaBarcodeScannerProvider <- $corodvaBarcodeScanner
    I/chromium( 1449): http://errors.angularjs.org/1.2.25/$injector/unpr?p0=%24corodvaBarcodeScannerProvider%20%3C-%20%24corodvaBarcodeScanner
    I/chromium( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:7703:12
    I/chromium( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11427:19
    I/chromium( 1449): at Object.getService [as get] (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11555:39)
    I/chromium( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11432:45
    I/chromium( 1449): at getService (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11555:39)
    I/chromium( 1449): at invoke (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11582:13)
    I/chromium( 1449): at Object.instantiate (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11602:23)
    I/chromium( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:14906:28
    I/chromium( 1449): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:14295:34
    I/chromium( 1449): at forEach (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:7957:20)", source: file:///android_asset/www/lib/ionic/js/ionic.bundle.js (17696)

    • Hi Aman,

      Just to confirm. You’ve added the following to your index.html:

      script src="ng-cordova.min.js"

      And you’ve added ngCordova to your module dependencies? You’ve also added the actual Apache Cordova plugin correct?

      Also, you’re running via an APK, not ionic serve correct?

      • Aman

        Yes to all. I do a ionic run android – this launches my application in genymotion

        PArt of my index.html

        Ionic Blank Starter

        Scan

        Part of my app.js
        var exampleApp = angular.module(‘starter’, [‘ionic’,’ngCordova’])

        .run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if(window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if(window.StatusBar) {
        StatusBar.styleDefault();
        }
        });
        });

        exampleApp.controller(“ExampleConroller”, function($scope,$corodvaBarcodeScanner){
        $scope.scanBarcode = function(){
        $cordovaBarcodeScanner.scan().then(function(ImageData){
        alert(“We got a barcode \n” +
        “Barcode text ” +ImageData.text + “\n” +
        “Barcode Format ” +ImageData.format + “\n” +
        “Cancelled “+ ImageData.cancelled);
        }, function(err){
        alert(“Scanning failed 🙁 “+err);
        });
        }

        • Hi Aman,

          Can you remove the following directories from your project and all of their content:

          project/platforms/android/ant-build
          project/platforms/android/ant-gen
          project/platforms/android/CordovaLib/ant-build
          project/platforms/android/CordovaLib/ant-gen

          Then instead of doing ionic run android, do ionic build android. When this completes, run the following command from the root of your project to install to Genymotion:

          adb install -r platforms/android/ant-build/yourapkname-debug.apk

          While replacing yourapkname with whatever yours is.

          If this doesn’t work, you’ve either missed a step in my tutorial, you are using too ancient of a device simulator in Genymotion, or your Ionic CLI and Cordova CLI are too out of date.

          I checked the plugin version and nothing has changed since I wrote this tutorial. I am using the code exactly how I presented it in one of my own apps.

          Please let me know if this gives you more success.

          Regards,

          • Aman

            Found it
            http://errors.angularjs.org/1.2.25/$injector/unpr?p0=%24corodvaBarcodeScannerProvider%20%3C-%20%24corodvaBarcodeScanner

            Spelling mistake in Cordova 🙁 of cordovaBarcodeScanner. I wish there was a way to find out these kind of typos.

            Also the camera on genymotion starts but when I put a barcode in front of it it does not recognize anything.

          • Hi Aman,

            That stinks! Spelling errors will get the best of all developers novice and pro.

            As for the reader recognizing barcodes. Make sure that the camera is not too far or too near to the barcode. Also make sure the camera auto focuses. When it successfully picks up the code, it will pause / freeze, then close the camera returning a response.

            As of right now, it appears everything is working. Should there be strangeness in the actual reading, you may want to bring it up with the developer of the Apache Cordova plugin.

  • m0nsterzd

    Hi Nic,

    Nice tutorial. Is there a way of setting the scanner to use portrait mode and not landscape?

    • Hi M0nsterzd,

      I wish Android supported portrait mode in this plugin. It works fine for iOS. See the following issue ticket:

      https://github.com/wildabeast/BarcodeScanner/issues/70

      It is a requested fix by many people. I’m hoping we get an update soon.

      Regards,

      • m0nsterzd

        Hi Nic,

        Thanks for your prompt reply. Pity about the portrait, however it still works very well in landscape and will make do for now.

        Regards

        • Hi m0nsterzd,

          No problem!

          Just a heads up, the current plugin version has a small problem with iOS 8, where the cancel button does not work. This is a very easy fix as mentioned by @peterfox1 in the following issue ticket:

          https://github.com/wildabeast/BarcodeScanner/issues/162

          Let me know if you run into issues altering the plugin source code to address this problem in your project.

          Regards,

  • Hi Nic,

    Thank you for awesome tutorials.

    Can you please tell me what will be in Html Side for $scope.scanBarcode ng-model=”scanBarcode”??

    I have done the same thing which you have mentioned .. its not giving me any error and not working even.

    Please help me. I am developing for android.

    Thanks
    Gaurav

    • Hi Gaurav,

      You can do something like this:

      It should be demonstrated in the video as well.

      Regards,

    • Thanks Nic, I have done this .

      • There must be an error in the logs if you followed my written and video tutorial exactly and its not working. Can you put your code on GitHub?

  • Hi Nic, Good tutorial. But it did not work. I put on github (https://github.com/100mendez/ionicbarcode).

    tks.

    • Before I look at your code I need more information.

      1. What didn’t work?
      2. What do the error logs say?
      3. Are you trying to use a device, simulator, or web browser? (which one)

      Let’s start with those three questions.

      Regards,

      • Hi Nic, I run on my devide( android 4.3 ) and simulator. The logs and returns is empty. the app read the QRCode but the return is empty… tks.

        • Just so I’m clear, neither of the following trigger in your code?:

          alert(imageData.text);
          console.log(“An error happened -> ” + error);

          If alert triggers, does it say null or undefined? Are you positive you are using a correctly formatted bar code that is not blurry or corrupt?

          Please let me know.

          Regards,

          • When I run on my Devide the alert does not Appear , only a black screen after reading the QRCODE . and- When I run the emulator , Appears empty alert . Shows the error in the log . Do you used the code ? what happens ?

          • I did not build your code, but everything looks correct.

            To my knowledge, you cannot use this plugin on a simulator. It will only work on the device.

            If you get a black screen after reading, I strongly believe you’re probably getting some kind of error. Things typically don’t misbehave without explanation. Can you tell me the results of ‘adb logcat’ when you try to scan something?

            Regards,

  • Guest

    Hi Nic, When I run on my Devide the alert does not Appear , only a black screen after reading the QRCODE . and- When I run the emulator , Appears empty alert . Shows the error in the log . Do you used the code ? what happens ? Many tks.

  • aimilios p

    hi nik thanks for the tut! its great job!
    Though there is a slight problem

    When you press back from the qr code screen, it fires back button in ionic so it goes to the previous screen..

    which i dont want do you have any solution for this?
    i tried $ionicPlatform.registerBackButtonAction but this func registers the global backbutton but i want it only for 1 page..

    • According to the plugin issue tracker, there are several reported cases of this.

      I personally haven’t experienced this problem, but being that others do, it is in the hands of the plugin developer. You may want to add to the issue comments in the tracker:

      https://github.com/wildabeast/BarcodeScanner/issues

      Regards,

  • Harvey Xia

    Hi Nic. Thanks for the tutorial first. It works perfectly on Android platform. I try to emulate it as ios. The scanner didn’t show up in the simulator. Do you have any idea for it? Thanks.

    • The iOS simulator does not support a camera so it is likely throwing an error.

      For this I suggest testing on the device.

      Regards,

  • Nesma

    I tried this sample and the black screen appears with the red line but it never detects any bar code . when i press back the alert is displayed empty. I am testing on google nexus 7 front camera can you help

    • Is the barcode / qr code clear and well lit? There are different levels of camera sensitivity for all devices.

      The red line also has to touch the entire code while focused.

      Regards,

      • Nesma

        It detects my code one time after lots of trials i dont know what is my problem

      • Nesma

        Thanks alot for your response i tried several times and managed to read the bar code once .. But when i try the same code again it is not working is it related to my camera or the plugin efficency or what

        • I believe it is your camera. I don’t have this problem on any of the devices I tested on.

          The only thing I can recommend is that you make sure everything is well lit, you keep a steady hand, and the camera focuses. Barcodes work on precision so it is very important everything is crystal clear.

          Regards,

  • Sebastián Lara

    Hi, the plugin documentation says that support “code 39” format (like this: http://www.mx5passion.com/espace_photos/grumpy-/VIN%20Sticker.jpg). When I get the imageData.text this is wrong, can you help me please?

  • Yannick Renner

    Hi Nic, I have a question… what are the information that the code return? How can I get it in my code? (i.e.: the name of a person from a visit card)

    • The imageData callback parameter will have everything you need. In my example I demonstrated imageData.text which will you will have to parse out to meet your needs, in your case contact data.

      • Yannick Renner

        Okkey, thank you very much

  • Guest

    Okkey, thank you very much 🙂

  • William K.

    Thanks a bunch, you’re a life saver

  • waqas

    Hi Nic Raboy
    i am using ng-cordovo barcode scanner plugin in ionic as above but i want to it when i open my app then scanner launch and when i click on back button it will close the app how it possible do you have any idea .
    thank you

    • I believe you’d have to edit the plugin in order to accomplish this. Currently it is only set up to go back in the stack. You’d have to swap the back button with close functionality via native code.

      I could be wrong on this though. You may want to ask this in the form of an issue ticket on the developers GitHub.

      Regards,

  • Mateenkaddy

    Hi Nic,

    How can I debug my code. I want to see the response message so that I can play with it.

  • SH Chong

    Hi Nic, thanks for your clear and simple tutorial guide, it was great.

    but i have miss some issues,

    when I onclick on the barcode scanner function i define, it will force close. so i try to deep into the code to see, and found that the error show :
    Didn’t find class “com.google.zxing.client.android.CaptureActivity”

    Did you have any idea for it?

  • sakthy

    Hi Nic, is there any way to set headers for the scanner?

    • What do you mean by “headers”?

      • sakthy

        Like navigation bar,,,

        • You would need to edit the native plugin code to do that. You might ask the developer of the plugin on that one, because I wouldn’t know.

          Regards,

          • sakthy

            I was trying the same, editing android and IOS native plugins. I was hoping for some simple solution 🙁 Thanks a lot. Nice tutorial btw 😉

  • Joindup

    Is it possible to automatically launch the scanner inside an Ionic App – preferably with an transparent mask overlay – so that users don’t have to tap a button to open the scanner?

    • In Ionic, a view will always be hit first. You can tell your controller to launch the scanner automatically, but there will still be a delay in that.

      If you wish to add overlays you would need to alter the native plugin. It is not something that can be done with Ionic.

      Regards,

  • Maxim Yakovlev

    Thanks Nick! Could you please let me know how I can display scan results into the needed template but not in alert after QR code has been scanned

    • I recommend you do some research on AngularJS. If you store the returned QR information in a $scope variable, it can be accessed from within your template as long as the template references the controller.

      Regards,

  • Alex Zhou

    a problem with ionic tap system, when i tap the ng-click=”scan()” link, the scan freeze, and i finally find out the problem is when i click/tap, the element is actually clicked twice, and that cause the barcodescanner freezed, is there a way to solve this? or use ngTouch in ionic?(which is not recommended by the ionic doc)

    • Please bring that up in the Ionic forums or in their GitHub issue tracker. Sounds like it could be a bug that needs to be fixed on their end.

      Regards,

      • Alex Zhou

        thanks for your reply, i initially put the ng-click in the ion-tab element, and when the scan result come back, $state.go(‘someview’), now i use on-touch=”scan()” in someview to solve the problem, i wonder if you have the same problem while using ng-click to call the scan()?

        • I never use on-touch, so I don’t have much information on that. I always use ng-click.

          To better troubleshoot, you may want to follow my guide 100% start to finish and see the results that it gives you. It will help you narrow down where the bug might be in your own code.

          Regards,

  • Fritz Hoste

    Works like a charm!

  • Raviteja Gunda

    I connected my nexus 5 phone and directly the app installed on it and working perfect. Now when I scan an item I have to store those mongodbusing node js. Any directions on that would be great.. Thanks

    • That is a very different topic that probably shouldn’t be discussed here.

      I might recommend Couchbase with the PouchDB library instead of MongoDB. You’ll probably have an easier time.

      Regards,

  • AndrewDinh

    Hi Nic. I enjoyed your tutorial! Thanks for posting.

    There are a few things I would suggest to improve. First of all, the tutorial is missing the final part where you went back into the index.html to add the ng-controller. Secondly, it’s missing the android build command in the command line. Thirdly, it’s missing the part where you assigned your angular module to the variable exampleApp so that you can define the controller later on. Of course, someone with a little bit of Angular knowledge would finally figure that out, but then again there might be complete beginners trying to follow your tutorial.

    I once followed another one of your tutorial to build a mobile application that uses the mobile camera to capture images but had to stop short of finishing because I keep running into build error even though I had Android SDK installed on my laptop no matter what I did. Since then, I did not have time to continue until recently. I was able to complete this project because before I started, I made sure my Android environment was set up correctly on my laptop.

    Anyway, good tutorial, although I would rate the difficulty at a higher level than newbie, because of the things I mentioned and Android SDK configuration.

    • Thanks for your in-depth feedback! I will note this for future tutorials. 🙂

  • Manish Kumar

    Hi nic,
    Thanks a lot for the tutorial.
    I followed your tutorial and build an app for scannig bar codes, It’s working fine but while holding camera too close to a bar code it scans part of the bar code, and returns random number/code. Can you suggest me how to fix this? Thanks in advance.

    • You might want to raise an issue with the plugin developer. Sounds like an issue with the plugin, not Apache Cordova or Ionic Framework.

      Regards,

  • Abdelmajid

    Hi thanks that was very good
    Please
    I have one issue, when I run the app in the phone, it gives nothing when I press scan.

  • Hello Nic, thaks for the great article!
    I tried to run this on phonegapp serve, test in my phone directly, but I have an erro when I press the button. The codova barcode plugin is undefined.
    The build command is required? When I test simple apps, do not use this command and works fine.

    • Please share your full error logs.

      Regards,

      • Nic, thank for your reponse.
        Here is the error log http://pastebin.com/VbTj5def

        • If you followed the tutorial exactly and are getting that error, it sounds like the plugin didn’t install correctly. Try reinstalling the plugin or wrapping the function in an onDeviceReady or $ionicPlatform.ready()

          Regards,

          • I’m testing on phonegap app in IPhone. Could this be?

          • Shouldn’t matter.

            Either the plugin didn’t install correctly or you need to wrap it in an onDeviceReady or $ionicPlatform.ready() to prevent a race condition. Looking at the commit history, the plugin hasn’t been changed in many months.

            Regards,

          • Nic, it seems like the barcode plugin dont install correctly. I’ve tested a vibration and camera plugin and works fine, but the barcode scanner still on error.
            Thanks for your help.

          • Maybe open an issue ticket on ngCordova?

          • I opened a ticket in the new plugin git repository: https://github.com/phonegap/phonegap-plugin-barcodescanner

  • Ramkrishn Saini

    I don’t want to show camera in full screen mode. I just want to show camera in half screen of device. I’m trying to show camera screen in a div. Can you please suggest me? Thank you

    • You’d have to alter the plugin itself since it is not currently possible in its current state. You may want to reach out to the plugin developer.

      Regards

      • Ramkrishn Saini

        thnk u ur quick reply. can u pls suggest alternate solution. I am using ionic and developing app for android and ios

        • There is no alternate solution. You need to alter the plugin if you want this functionality.

          Regards,

  • Omar

    Its Work!!! ,1000000 Thanks!! 🙂

  • Santhosh Billu

    Nice article. Can you please send full index.html and app.js file?

    Thanks in advance.

  • Clint Magnus

    Hello, Thank you for tuto, very helpful, but I have a question :
    How can I know more feature about Object returned ? ( imageData in your example )
    for example i try with VCard QR code generator and imageData.text return me that
    BEGIN:VCARD
    VERSION:2.1
    FN:FirstName
    N:FirstName;LastName
    TITLE:Developer
    TEL;WORK;VOICE:+32 (0)xx xx xx xx
    EMAIL;HOME;INTERNET:[email protected]
    URL:www.google.com/
    END:VCARD

    • Yes, it is up to you to parse and make sense of the data returned. The QR code is just a type of barcode. It just contains text data for you to use how you want.

      Regards,

      • Clint Magnus

        Thank for the reply

  • Frank Barrett

    Thanks for the awesome tutorial! I managed to get mine working. Do you by any chance know the correct way to edit the scanner’s interface? Like changing the size and color of the green square and red line?

    • You’ll have to edit the native plugin code if you want to change the interface. This cannot be done via Ionic or PhoneGap.

      Regards,

      • Frank Barrett

        I see. That’s what I was afraid of. Oh well, thanks for the response!

  • Na14

    Hi Nic,

    I just tried running this and I can get the camera working. When I try to retrieve the data I always get a cancelled: true value and then the .text and .format fields are empty. Is there something I’m missing?

    • So you’re saying it detects the barcode, but just returns nothing? Or it doesn’t even detect the bar code?

      • Na14

        It detects the barcode and says “Found URL” or “Found text” but then returns cancelled:true.

        • Sounds pretty odd!

          I think you should open a ticket with the plugin developer. Maybe they introduced a bug in one of the more recent versions.

          Regards,

  • Thananwat Thanabowornsawat

    Hi Nic,
    Please advise I coding same this example but I not’can scan barcode repeat same barcode.

    • What do your error logs say?

      • Thananwat Thanabowornsawat

        status : not show anything.
        The mobile android version 4.3
        and New mobile android 5.0.2 up. It works.

        • You’d have to contact the plugin developer in regards to adding camera switching as a feature. This cannot be done via Ionic unless the plugin supports it which I don’t believe it does.

          Regards,

  • Nice blog posts =]

  • Carlos Reyes

    Hi Nic i’m having a problem, i’ve already installed everything twice but still getting the same reference error “ReferenceError: cordova is not defined” in the chrome console and on the device, little help?

    • Carlos Reyes

      don’t worry, i solved 🙂

      • Rajah

        Hey Carlos Reyes How You Can Rectified please tell for feature reference.

      • Tim Kens

        Hi Carlos

        I also have got same problem which you had last

        “ReferenceError: cordova is not defined”

        I am now testing it in chrome using Ionic serve

        But you posted you had solved it.

        Could you tell me the solution ?

        Cheers
        Tim

        • Do not use a web browser and do not use ionic serve. Those are the two worst things you can use when developing Ionic Framework applications.

          The web browser cannot understand native device code such as the barcode scanner which is why you are getting a cordova not defined error. If you build and install to the device, your problem should go away.

          Regards,

  • Arulmozhi

    Hi Nic, When i run bar-code scanner i have found some issue like Cordova is not defined.I trying in emulator and also device it shows same error.

    • Please paste your logs rather than using a screenshot. Pictures of logs make it very difficult to inspect.

      Regards,

      • Arulmozhi

        Hi Nic, this controller works on app.js page but when we trying to use in separate controller it doesn’t works. can you help me how to initialize the separate controller to use this code

        • Please paste your logs. An infinite amount of reasons why it doesn’t work, so I can’t take any guesses without getting more information.

          Regards,

          • Arulmozhi

            this is what my console log shows.

            Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help, check http://xhr.spec.whatwg.org/.
            ionic.bundle.js:21157 ReferenceError: cordova is not defined at Object.scan (http://127.0.0.1:52534/www/js/ng-cordova.min.js:7:5721)

            <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            this is app.js page

            var exampleApp = angular.module(‘starter’, [‘ionic’, ‘ngCordova’, ‘starter.controllers’]);
            exampleApp.run(function($ionicPlatform) {
            $ionicPlatform.ready(function() {
            if(window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if(window.StatusBar) {
            StatusBar.styleDefault();
            }
            });
            })
            exampleApp.config(function($stateProvider, $urlRouterProvider) {
            $stateProvider
            .state(‘app’, {
            url: ‘/app’,
            //abstract: true,
            templateUrl: ‘templates/home.html’,
            controller: ‘AppCtrl’
            });
            $urlRouterProvider.otherwise(‘/app’);
            });
            <<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

            this is my controller.js

            var exampleApp = angular.module(‘starter.controllers’, [])
            exampleApp.controller(‘AppCtrl’, function ($scope, $rootScope, $cordovaBarcodeScanner, $ionicPlatform) {
            $scope.scanBarcode = function() {
            $cordovaBarcodeScanner.scan().then(function(imageData) {
            alert(imageData.text);
            console.log(“Barcode Format -> ” + imageData.format);
            console.log(“Cancelled -> ” + imageData.cancelled);
            }, function(error) {
            console.log(“An error happened -> ” + error);
            });
            };
            });
            <<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            this is home.html

            Head

            scan

          • What is http://127.0.0.1:52534? Are you using Ionic Server, Ionic Live-Reload, or Ionic View? You shouldn’t use any of those when working with native device plugins.

            Please let me know where the IP is coming from in your setup (and yes I know it is local machine).

            Regards,

          • Jay

            Hi Nic. Thanks your tutorial. Those posts help me a lot. I have a problem. You said don’t use Ionic serve, Ionic View, and web browser. But I don’t know how to running this application without Ionic View and web browser. Is there any post I should read?

          • If your doing Android you need to run ‘ionic build android’ and then install the apk to the device or simulator. If you’re doing iOS you need to run ‘ionic build iOS’ and open the Xcode project generated. Then you can run on the device or simulator.

            Best,

  • Marcelo Galvão

    Very good!!

  • Rakesh Boinepalli

    ng-cordova barcode scanner doesn’t scan CODE 128 barcodes. Any recommendations on how to overcome this issue?.

    • It should work. You might want to contact the plugin developer (not ng-cordova developer). I pulled the list from the developers read me.

  • Guille Acosta

    It’s exactly what I was looking for. I’ll try and let you know if all works ok._
    Thanks!

    • No problem. Enjoy 🙂

      • Guille Acosta

        Worked! Thanks again Nic.

  • GREAATTT Thx

  • Hi nic,
    is there any idea how to customize the barcode scanner layout?,
    b’coz the default one is too ugly. :'(

    • You cannot style it without changing the plugin itself. You’d have to talk to the plugin developer.

      Regards,

  • love ya!

  • Sydney Collins

    Is there a way to customize the look and feel of the scanner , I wish to make the square bigger can you help me?

    • The only way to do this is to make changes to the plugin itself. This would require knowing native Objective-C and Java.

      You might contact the plugin developer suggesting such options.

      Regards,

  • Henrique Schmidt

    Great! It worked perfectly, exactly what I wanted!

    • No problem. I’m glad you found it useful 🙂

  • Jorge

    Thanks Nic for this example. Its possible scan the barcode and in the same things showing an html5 ? I need to capture qrcodes but I need display several information on the screen.

    • I’m not too sure what you’re saying. Do you want to display information after scanning the QR code, or information on the scanner screen?

      • Jorge

        Hi, I want to display the information on the scanner screen.

        • This is not possible without altering the plugin itself. It is not something you can do via JavaScript.

          Regards,

          • Jorge

            Thanks, i will work in asolution for it. Regards

  • Santiago

    I done all steps like you posted here, but my button doesn’t work, Can you help me?

  • HAT.

    Amazing job, thanks!

  • HAT.

    Working just fine with iPhone ionic view app!

  • Jesus Miguel Isaac

    when i scan a second time the alert its empty…i cant hit with the problem. Any idea? (sry my creepy english)

    • Jesus Miguel Isaac

      done, the problem its solved when i change the ng-click for an on-touch.
      gl hf!

  • Jessica Thompson

    Hi Nic,

    I am wanting to use the barcode plugin in my ionic app. I want the user to be able to scan a barcode of a food product and it then tell the user the allergens within that product or what the product contains. this can just be a prototype so this can just be on one product. How would I go about doing this?

    thank you

    • You would either need to store all these products and product information in a database bundled within your application or you’d need to build a REST server with a database of products and request the data as you get barcode information.

      • Jessica Thompson

        Thank you for your response.
        Which method do you recommend me using out of th two options?

        • I recommend both. Web requests are slow so you should design your application to only make them if the product doesn’t already exist in your local database. You can populate your local database by shipping the latest with every release of your app or by implementing a sync.

          Best,

  • Benjamim Marcos de Castro Juni

    Is it possible to change prompt text that says “place the barcode inside the viewfinder…”

    • You’d have to alter the actual plugin. This cannot be done via JavaScript in Ionic.

  • Vrushank

    Nic,

    Very good example, appreciate.
    Run perfectly on my android device, I can able to scan QRBarcode and 1D but I can’t able to scan PDF417.
    Need help.

    Thanks!

    • You’d have to contact the plugin developer requesting support for more barcodes.

  • Arulmozhi

    Hi Nic,
    This is wonderful post. it works fine in all devices but in samsung it doesn’t works properly. where it scans the first items and shows the correct result but when i scan second item the camera doesn’t close it scans again even found product after that it doesn’t show the result. can you help in that!!!

    • You should raise an issue ticket with the plugin developer. Sounds like an issue with the native code.

  • Nic, please help, i get “error initializing cordova class not found”. I have already installed my app on my android device. I get the error when i try to scan qr code. Any advice?

    • Please share your full logs.

      Regards,

  • Marin Postma

    when emulating on ios i get error THREAD WARNING: [‘BarcodeScanner’] took ‘10.642090’ ms. Plugin should use a background thread, what did i do wrong??

    • That looks like a typical plugin warning and shouldn’t be an issue.

  • Khoa Nguyễn

    The barcode return is empty. Please help me…

  • Carlos Reyes

    Hi Nic, i have a working app on ionic view, read the url and all after clicking a button, but when i build the apk and install it on my android phone the button does nothing, what could it be?, in the console does not appear any build error

    • What do your runtime logs say?

      • Carlos Reyes

        where can i find that?

          • Carlos Reyes

            thanks Nic really helpfull, i had to install universal drivers for my android phone, if anyone has a trouble finding their smartphone drivers this help me a lot http://adbdriver.com/

            now i have these errors in the logcat Nic

            I/chromium(29756): [INFO:CONSOLE(105)] “Uncaught Error: cordova already defined”, source: file:///android_asset/www/cordova.js (105)

            E/AndroidProtocolHandler(29756): Unable to open asset URL: file:///android_asset/www/cordova_plugins.js

          • Sounds like you defined something twice.

          • Carlos Reyes

            Ups yes cordova.js was defined twice, but still it doesn’t work :/, the odd part it’s that in ionic view it works

          • I don’t for any circumstance recommend using ionic view, ionic serve, ionic live-reload. These are not true mobile experiences and is further backed up by your inconsistencies between the two. Long term you’ll do better not even including it in your development workflow.

            Beyond that, are your logs the same now that you’ve removed the double occurrence?

          • Carlos Reyes

            Now it works, Inappbrowser plugin it’s need it to open the url in a phone browser, thanks for sharing your knowlege with us Nic 😀

          • No problem

  • donny gunawan

    Hi Buddy ^_^ please add tutorial for encode(generate) some string to qr image also. Big Thanks.

  • Omygddd

    Hi dear thks a lot for sahring.
    All works great except the fact that after scanning and retrieving barcode i wish to redirect user to another view and i am unable to do it work.

    Any idea ? $state.go(‘view’,{barcode:barcoderetrieved}) does not work… make 4 hours i am looking for !!!! Grrrrr

    Please help me i become mad !

    Thks a lot

      • Omygddd

        Hello Nic And thanks for your reply,

        Below my controller code maybe it’s more comprehensive like that. Sorry i wanted to be short in my message.

        I think your explanation will be really helpfull for lot of people.

      • Omygddd

        Nic i read attentively what you wrote about comments.

        I am running your code on android and it works as you describe. I just want in the controller of barcode to redirect user to another view with barcode retrieved by scanner.

        I use : $state.go(‘resultscan’,{id:barcodeData.text}); This code is in the success aera and i cant make it works.

        I Hope my message respect your guidelines now.

        • Well, I am still missing information which is why I redirected you to the link in my previous comment.

          What doesn’t work? Does it not navigate? Does your Android device explode? I don’t know what doesn’t work.
          What do your logs say?
          What version of Android are you using?
          Are you using a device or simulator?

          I can’t help if I don’t have all the details.

          Regards,

          • Omygddd

            Hi Nic thanks for your precious time.

            i put a little code inside the success function of the barcode controller : $state.go(‘resultscan’,{id:barcodeData.text});

            What does not work : after retrieving barcode i want to redirect to a specific view with barcode as parameter > NOT WORKING
            log says : TypeError: Cannot read property ‘go’ of undefined // code : $state.go(‘resultscan’,{id:barcodeData.text});
            Android Version : 5.1
            Running on a device

            Hope its more clear like that ^_^

          • Well, “NOT WORKING” does not help me. I know you probably think I’m giving you a hard time, but if you follow what I say, you’ll benefit in the future. With that said, how is it not working? Is it not navigating to the desired page? Does the desired page not contain the barcode data after you navigate to it? You see where I’m going with this? I can’t read your mind, only what you type.

            However, the log did help. If ‘$state’ is undefined, it probably means you didn’t inject it into your controller.

            Next time you ask a question in a blog, forum board, stack overflow, etc., think about how you ask your questions. I guarantee you get better help when you supply better information.

            Regards,

          • Omygddd

            I understand what you mean “NOT WORKING” is too large. it means don’t go to other view. Nothing happens after the codebar is correctly retrieved…

            Hope its more clear and sorry i am a noob ;(

  • prashantvictory

    Do you have this full code available anywhere for download? As I made it in the same manner as you advised, but it is not working for me when I am testing in simulator.

    • Sorry, but I don’t package the code to my free content, only my premium content. If the tutorial and video is not working I’m happy to answer questions, but not package the code for you.

      • prashantvictory

        OK, I think I made all same as you did in youtube video, but when I run my app and click “Scan” button nothing happens. I am running app in simulator which comes with ionic lab.

        • Plugins that use the camera should not be tested via the simulator because most simulators have limited support for the camera.

          Regards,

  • Firdaus Hm

    when i try “ionic build android”, it is not working , display “it cannot locate the path”… help?

  • Yury Horbach

    I am using this plugin in a Windows 10 UAP. The scan() fires an error Reference error: ZXing is undefined.
    Any idea?

    • Last I checked, Ionic Framework does not support Windows 10.

      • Yury Horbach

        It does now and everything else works, except this plugin. On the plugin doc site they also claim to support win10. So I hope the issue lies elsewhere in my own project.

        • Show me on the official Ionic website that it is supported. The home page had no indication beyond iOS and Android.

          In any scenario, supported or not, I have no way to test. I am a Mac user with no Windows devices.

          Regards,

          • Yury Horbach

            You can read it here: http://blog.ionic.io/announcing-ionic-1-2/

            Now the good news: as expected, I found the issue in my own project. I had to build for ARM architecture before installing the app on the phone (default is anyCPU). Now it works like charm!
            All in all, I am heavily impressed with how my ionic app performs on Lumia 550 which is an entry level device indeed.

          • Thanks for sharing. I was not aware they slipped it in 🙂

  • Is there any plugin for generating a qr code or barcode?

  • Amit Batra

    Hey nic Nice tutorial, is there any way to fix the background camera height and width opening with the scanner,i dont want my camera to occupy the whole screen

    • I’m not sure what you’re talking about. Can you provide a screenshot?

      • Amit Batra

        Hey Nic ,below you can find The screenshot.Now as you can see the camera Apart from Rectangular view occupies full screen .so is there any kind of setting to fix the camera height and width or to customize the whole screen ,and one thing also is there any way to add close button on this screen because if we use the same plugin in ios the scanner will be launched but if there is nothing to scan user won’t be able to close it without scanning the barcode.

        • That looks normal to me. The Zxing library that this plugin uses was designed this way to have a section of the screen that reads the barcodes.

          You’d have to modify the core library itself or create your own library if you want to let the entire camera area scan for barcodes.

          Best,

          • Amit Batra

            ok i tried it but nothing happened , i tried to fix the frame width in the core library and launched the whole application into my cellphone but no results it’s still same……

            so is there any Possibility to add a close button on the screen when the scanner is launched…

            And I’am having some more issue’s related to plugin like it takes a lot of time to scan bar-code and after scanning it takes 2-3 seconds of delay and then comes back to the that screen from where it was launched.. so is there any way to eradicate the delay which occurs while scanning an item..

            Below i’m attaching a screenshot…Its where the delay problem occurs

          • Your barcode doesn’t seem clear. Different cameras will have different quality. In the right lighting, when the camera focuses, it will read the code.

            If you need to make any revisions to the plugin such as add a back button or develop your own plugin, I won’t be able to help you.

            Best,

  • Cesar

    any way to declare scan only QRcodes?

  • Nicolás Peralta Sáez

    Thanks! nice tutorial, it worked fine.

    But i was wondering
    How can we instead of using alert, make the qr code go to our browser?
    i tried with window.open(imageData.text) but it doesnt work.

    • What doesn’t work about it? I need more information.

      • Nicolás Peralta Sáez

        I would like to instead of getting an alert of the QR that got scanned, get it opened on a webbrowser. How can i do that??

        Thank you 😀

        • You can install the InAppBrowser plugin and launch it in the callback instead of showing an alert

  • Leonardo Mendonça Piazzoli

    Hi Nic, how to change the string “Place a barcode inside the view finder rectangle to scan it.” that shows when you open the scanner? Thank’s.

    • You’d need to alter the native plugin code.

      • Leonardo Mendonça Piazzoli

        I tried, but it did not work.
        Changed string.xml | Enquadre o código de barras a ser lido..
        No success :(.

        • You probably want to contact the plugin developer.

        • Rafael Amorim

          Have you been successful changing this text? I’m also trying to change that to pt-br and no success so far.

          • Leonardo Mendonça Piazzoli

            Yes I did.
            – Try to clean and rebuild the project.
            – Try change in all xml that constains the string.

          • Rafael Amorim

            Thanks!!

  • Itsr nd

    Hello Guys, My code works properly on most of the platform but gives error “unfortunately app stopped working” on 4.4. when executions reaches to “$cordovaBarcodeScanner.scan().then(function(imageData)” it shows error. My code is as follow :

    exampleApp.controller(“ExampleController”,function($scope,$cordovaBarcodeScanner){
    $scope.scanBarcode = function(){
    alert(“In function”);
    $cordovaBarcodeScanner.scan().then(function(imageData){
    alert(“In function1”);
    //alert(“Format = “+imageData.format);
    document.getElementById(‘customer_bar_id’).value = imageData.text;
    alert(“In function2”);
    $(‘#customer_bar_id’).show();
    alert(“In function”);
    $(‘#customer_bar_search’).show();
    },function(error){
    alert(“An error happened = “+error);
    });
    }
    });

    Please help. Thank You.

  • Deel

    Hi very nice tutorial.
    It worked but it use the clipboard to copy imageData.text
    I don’t want that, how i can fix it ?
    Best Regards,
    Deel

    • I don’t think it uses the clipboard, but honestly I never checked. If it does, you’d have to alter the native plugin source code or contact the plugin developer.

      Best,

    • Naoki Ishigaki

      I am facing same issue on Android.
      I read the android source code and think it is caused by “com.google.zxing.client.android.captureactivity.jar”.
      Because, There is a code like “clipboard.setText(displayContents)”.
      If you fix it , I am wandering if you tell me that.
      Sincerely, Naoki.

    • Naoki Ishigaki

      Hi, I fix it.
      you can add this plugin from here.
      https://github.com/nao0515ki/phonegap-plugin-barcodescanner

      • Deel

        Thanks a lot bro ! This is so impresive

  • Amir

    Hello, I have a problem when try to input “ionic build ios” which result in this:

    /usr/local/lib/node_modules/cordova/node_modules/update-notifier/node_modules/configstore/index.js:53

    Error: EACCES: permission denied, open ‘/Users/Amir117/.config/configstore/update-notifier-cordova.json’

    You don’t have access to this file.

    How to solve this problem? I tried with sudo also but this comes out:

    xcode-select: error: tool ‘xcodebuild’ requires Xcode, but active developer directory ‘/Library/Developer/CommandLineTools’ is a command line tools instance

    ERROR building one of the platforms: Error: /Users/Amir117/Desktop/IonicProject/platforms/ios/cordova/build: Command failed with exit code 2

    You may not have the required environment or OS to build this project

    Error: /Users/Amir117/Desktop/IonicProject/platforms/ios/cordova/build: Command failed with exit code 2

    • Your environment is not configured correctly. Fix the permission issues in your home directory and it should work. Never use sudo when building.

      Best,

      • Amir

        Hello again, I’m sorry, can you tell me how to fix the permission issues, I don’t really know how to solve it.. thanks again in advance for your help

        • Well you want to make sure everything in your home directory has your user account as the owner. When you run

          ls -la

          It will tell you the permissions and owner to each file and directory. You can use chown to change ownership. I suggest you read up on the Unix documentation for this.

          Regards,

  • Bae Yongchae

    It’s can’t read EAN 13 but can read QR Code.

    • What platform? What version?

      The more information you give me the better I can help you out.

      Best,

      • Bae Yongchae

        i use android 4.4.2 .
        Thank you Nic

        • That is weird, it should work according to the documentation. If I were you, I’d open an issue ticket with the plugin developer.

          Best,

          • Bae Yongchae

            Do you have complete this project file for share?

          • Sorry, but I don’t share the full projects to my free content. The blog and the step by step video should be more than enough to get you where you need to be.

            If you are able to scan QR codes, but not other codes I would contact the plugin developer.

            Best,

          • Bae Yongchae

            Thank you Nic

          • No problem!

  • Petřík Šmitmajer

    Hello everyone,

    I have a one small problem 🙂

    I scan QR Code very fast but result is that return empty string, it make autofocus I guss

    I have problem with scan qr code with autofocus I guss, becouse when I
    try scan qr code by barcode scanner so is too fast and it does’t
    recognize content of qr code and return empty string. I think that even
    the camera not enough focus on qr code and barode scanner immediately
    scan fuzzy qr code and result is empty string.

    Sometime the scanner try scanning qr code twice immediately again but anyway barcode scanner return empty string…
    I have samsung galaxy S4 mini with 8 Mpx. – android
    id=”phonegap-plugin-barcodescanner” version=”4.1.0″

    $scope.scanBarcode = function () {
    $ionicPlatform.ready(function () {
    $cordovaBarcodeScanner.scan().then(function (imageData) {
    if (imageData.cancelled) {
    alert(‘Please scan again’);
    } else {
    $state.go(‘app.tabsController.testDetail’, { testDetailId: imageData.text });
    }
    }, function (error) {
    });

    });

    }

    Is it any way how to improve this code for better recognition of
    content of qr code? or set autofocus by handle click to display?

    I am apologize for my english.

    Thank You very much for your response.

    • I recommend opening an issue ticket with the plugin developer. If there are timing issues with the plugin itself, it is with the native code and not something we can correct with JavaScript.

      Best,

      • Petřík Šmitmajer

        I find solution, I must replace on-touch instead of ng-click and its working, becouse when i use ng-click so sometimes the activity of scan start twice and scanner scan code twotimes imediately after first scan and in this case result was empty string.

        • George Vrynios

          Very useful article, and Petřík Šmitmajer I had the same problem and thanks to your solution now works to me.

  • kashshah43

    Hey what if I want to exit from scanning screen in IOS?

    • As of right now I don’t think so. You might open a ticket with the plugin developer asking this question. Might be a good revision to be added to the plugin itself.

      Best,

      • kashshah43

        Ohh okay…!

  • Sammy Israwi Yordi

    Hello all!
    I just tried this tutorial, and there seems to be an issue when launching the scanner. On a MotoX 2nd Gen running Android 6.0, when pressing the button that launches he camera, an pop ups shows up saying that a device restart may be required. Camera works with any other app. I asked around and did not get an answer, I was hoping I would get one here.

    Thank you!

  • Saravana selvan

    Hi Nic. My camera opens and the scan screen is displayed. But when I try to scan a QR Code nothing happens. The camera is still open without scanning. Can you help me with it. Thanks for the nice article.

    • Your camera needs to focus otherwise it won’t recognize the barcode. I’ve heard of issues on lower quality devices that have a weaker camera.

      Try a different bar code or different device?

      Best,

  • Ermal Feka

    hi Nic, I updated my Android to version 6.0.1 and the plugin doesn’t work anymore.
    Can you help me ???

    • What do your logs say?

      • Ermal Feka

        The application displays the following message: < msg_camera_framework_bug >
        After some research on the internet, I found that the problem comes from the Android permissions.
        The only solution I found is to manually allow my app to use the camera in the Android settings.
        Do you have a solution that wouldn’t require the user to do that ?

        • That is a question best asked to the plugin developer.

  • Jorge Cascante

    Hey Nic. Nice article. I’m in a similar situation. I have to develop an app the reads bar code but do it also using bluetooth scanners (like this one https://www.socketmobile.com/home/?languageRedirect=true) so I wanted to know your take on this issue. I haven’t done much research yet, but how do you think ionic would couple with third party external scanners? Would it be demanding or expecting too much from ionic?

  • Divya Madavan

    i followed step by step but My application home screen loading it shows header bar and scan now button..if i click the buttton nothing would be happening.scanner page(camera) will not be loading how to fix it? I added plugin also.Any body guide me how to do this.am very new to angularJS.

    • What do your logs say?

      • Divya Madavan

        Still I Didn’t Solve my issue.

        In my Build output I have the following:

        ionic.bundle.min.js’ could not be read from the specified location due to error ‘Exception of type ‘TypeScriptSourceMapReader.SourceMapReadFailedException’ was thrown.

        In my Javascript Language Service I have the following error:

        Referenced file ‘cordova.js’ not found.? Have any solution for my problem.

  • Aisha El Allam

    Whenever I press scan I get this error;

    • Aisha El Allam

      never mind i forgot the main thing which is the plugin itself

  • faresallolo

    Great tutorial as usual. I wonder how to wrap it in a factory or service? would you kindly give hints ?

  • Venkat

    Hi Nic, How to Scan QR Code inside a specific camera height and width? Please help me on this.

    • I don’t know what you’re talking about. Want to give me more information?

  • works great! thnx Nic so much for this 😉 very helpful.

    • Glad I was able to help 🙂

      • BTW, thnx for your courses & tuts…really in-depth and good grounding material. I’d be very interested in your offering more infor on Angular2 and Ionic2. Still early but, your delivery is what’s great and I think many of us would benefit in the dev community. Just my 2 cents. Bless. Ciao! Lis

        • Thanks for the compliment!

          I have a lot of Ionic 2 content coming, but if you’d like more depth, you might consider becoming a premium member. I’ll be showing how to create complex applications in that content.

          https://www.thepolyglotdeveloper.com/category/premium-membership/

          Best,

          • Nic…how would I parse a QR that i created that is in JSON and then I read it with this scanner…QR is JSON data with id, firstname, lastname and then automatically fill 3 input fields in a view? I’m trying different things but tricky. Can u plz tell me? Thnx.

          • I really need to do this fast for an app i’m working on right now and more stuff…btw…I took ur premium. nice stuff! thnx lots 😉

          • Ignoring your form elements, what is the result when you scan? Best to do one thing at a time and start with the QR before trying to do more.

          • I pick up the text from the scan and it alerts as index.html with {“id”: “12345”,”firstname”: “Jimmy”, “lastname”: “Sands”} shown. i’m using e.g. ng-bind={{imageData.text.firstname}} to display an I’ve also tried to use just{{text.firstname}} as well. the div has ngController from the scanner controller, the same

          • I believe imageData.text is string data not a JavaScript object. You’ll probably want to call JSON.parse on it to turn it into an object.

            Let me know if that helps.

          • yes, i figured that out. so what i did is to set the contents of the text from the scan like this:
            // parse imageData first from the Object imageData:
            var parsed = imageData.text;
            // create a new array with [] … same as new Array();
            var arr = [];
            // push contents of parsed data, now JSON data to the array arr:
            for(var x in parsed){
            arr.push(parsed[x])
            }
            // setup $scope variables to use in the i
            // nput using ng-model in view:
            $scope.idn = arr[0];
            $scope.firstname = arr[1];
            $scope.lastname = arr[2];

          • I think you’re over complicating it. Did you try this:

            $scope.obj = JSON.parse(imageData.text);

            Then in your HTML file you can do something like:

            {{obj.firstname}}

            Make sense?

          • nope 😉 i’ll look more into it. really got me on this one.

          • I put in the input tag ng-show={{obj.id}} btw and stil couldn’t get it to show

          • got it done: the BarcodeCtrl needed to be put in the ion-content section/tag and and then ng-model=”obj.id” in the input section/tag and voila, worked like a charm! Done.

          • Fantastic 🙂

          • your help was instrumental in getting this done for me Nic so I could experiment a bit and u put me on the right track for sure! thnx again. bless 😉 Lis

          • Nic…what’s your idea to change the square crosshair to a red vertically-moving up/down red line? LMK plz if you can. Thnx so much. Bless

          • You’d have to edit the native code to the plugin. This cannot be done via Ionic and Angular.

          • Ja. That’s what I thought too. I would like to find out how I can include my own animated crosshair-square…gif, animation, et…and where I need to make that change. If you come across this, plz LMK. Thnx Nic.

          • Nic hi…I set up my project to default to portrait-only in the ionic files and in the ios build to portrait-only show up and also i setup the upside-down enabled. Works fine in ios. But the ionic view app doesn’t work for this setting. Do you know fix or issues surrounding this? Plz LMK when u get a chance. Thnx. Lis

          • Ionic View is only a wrapper for serving an application. I don’t recommend using it, ionic serve, or ionic live reload. Using any of those three are sure ways to run into problems.

  • sbakhtiari

    It works perfectly as long as I build on my own pc. When I use “ionic package build” the result package can not open scanner and says: “Cannot call method ‘scan’ of undefined”, as if the plug-in is not installed.
    I need to use “ionic package build”, so I can get signed binaries for both Android and iOS to submit to the stores.
    The problem is for both Android or iOS, when I build locally it works. Looks like “ionic package” can not build this plug-in. I have already used other ngCordova plug-ins with no problem (like Camera, …).

    • Cloud build platforms do not work properly with ALL plugins which is why I strongly recommend against using these solutions. Your best bet is to build locally and release.

  • Bruno Casotto

    Hello, first I’m sorry for my english.
    I made all like you but I receive a error, help me please:

    Log of chrome:
    ng-cordova.min.js:7 Uncaught ReferenceError: angular is not defined(anonymous function) @ ng-cordova.min.js:7(anonymous function) @ ng-cordova.min.js:9
    ionic.bundle.js:13415 Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
    Error: [$injector:modulerr] Failed to instantiate module ngCordova due to:
    Error: [$injector:nomod] Module ‘ngCordova’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
    http://errors.angularjs.org/1.5.3/$injector/nomod?p0=ngCordova
    at http://localhost:8101/lib/ionic/js/ionic.bundle.js:13415:12
    at http://localhost:8101/lib/ionic/js/ionic.bundle.js:15381:17
    at ensure (http://localhost:8101/lib/ionic/js/ionic.bundle.js:15305:38)
    at module (http://localhost:8101/lib/ionic/js/ionic.bundle.js:15379:14)
    at http://localhost:8101/lib/ionic/js/ionic.bundle.js:17871:22
    at forEach (http://localhost:8101/lib/ionic/js/ionic.bundle.js:13668:20)
    at loadModules (http://localhost:8101/lib/ionic/js/ionic.bundle.js:17855:5)
    at http://localhost:8101/lib/ionic/js/ionic.bundle.js:17872:40
    at forEach (http://localhost:8101/lib/ionic/js/ionic.bundle.js:13668:20)
    at loadModules (http://localhost:8101/lib/ionic/js/ionic.bundle.js:17855:5)
    http://errors.angularjs.org/1.5.3/$injector/modulerr?p0=ngCordova&p1=Error%…%3A%2F%2Flocalhost%3A8101%2Flib%2Fionic%2Fjs%2Fionic.bundle.js%3A17855%3A5)
    at http://localhost:8101/lib/ionic/js/ionic.bundle.js:13415:12
    at http://localhost:8101/lib/ionic/js/ionic.bundle.js:17894:15
    at forEach (http://localhost:8101/lib/ionic/js/ionic.bundle.js:13668:20)
    at loadModules (http://localhost:8101/lib/ionic/js/ionic.bundle.js:17855:5)
    at http://localhost:8101/lib/ionic/js/ionic.bundle.js:17872:40
    at forEach (http://localhost:8101/lib/ionic/js/ionic.bundle.js:13668:20)
    at loadModules (http://localhost:8101/lib/ionic/js/ionic.bundle.js:17855:5)
    at createInjector (http://localhost:8101/lib/ionic/js/ionic.bundle.js:17777:19)
    at doBootstrap (http://localhost:8101/lib/ionic/js/ionic.bundle.js:15057:20)
    at bootstrap (http://localhost:8101/lib/ionic/js/ionic.bundle.js:15078:12)
    http://errors.angularjs.org/1.5.3/$injector/modulerr?p0=starter&p1=Error%3A…3A%2F%2Flocalhost%3A8101%2Flib%2Fionic%2Fjs%2Fionic.bundle.js%3A15078%3A12)(anonymous function) @ ionic.bundle.js:13415(anonymous function) @ ionic.bundle.js:17894forEach @ ionic.bundle.js:13668loadModules @ ionic.bundle.js:17855createInjector @ ionic.bundle.js:17777doBootstrap @ ionic.bundle.js:15057bootstrap @ ionic.bundle.js:15078angularInit @ ionic.bundle.js:14963(anonymous function) @ ionic.bundle.js:44056trigger @ ionic.bundle.js:16474defaultHandlerWrapper @ ionic.bundle.js:16764eventHandler @ ionic.bundle.js:16752

  • disqus_j3uT35dkMq

    Is it possible to implement MRZ scanner using ionic framework? Can’t seem to find any information on this!

    • What is the MRZ scanner?

      • disqus_j3uT35dkMq

        Scans the MRZ (Machine Readable Zone) code of a passport and extract the firstname, lastname, passport number, nationality, date of birth, expiration date

  • Alberto

    Your a master dear Nic Raboy, but many of your tutorials have serious problems when the app run in device.

    • Like what kind of problems? You didn’t give me any details

  • Andy

    how can we customize scanning page layout ? Any one has any Idea ?

  • Marcel Izgin

    How can you make it not run in full screen mode but within a specifiable div?

    • I don’t believe this plugin is capable

  • Wolker Wegner

    Still works! Really nice job on this tutorial, thanks!

  • Amit Karmakar

    Hi Nick!! I am one of the follower.I like your post and honestly helped me lot of situations.
    Nick i just want know how to implement multiple Bar Code Or QR Code in Ionic 1 Application?
    Can you please send some code?

    • I don’t send code. You won’t learn anything if I did that.

      How about sharing what you’ve tried and what problems you’re facing. I’ll try to help you with that.

      Best,

      • Amit Karmakar

        Any clue or any start activity, how can i start?

    • Amit Karmakar

      Any clue or any start activity, how i start?

  • Amit Karmakar

    Hello Nic!! I have implemented it successfully but i need to know how can i get all Bar code related data after scan.Here i am geeing only the unique number.I need all info related to Bar code. Please give some Idea.

    • Barcodes only store codes. You should store those codes in a database with real data. After a scan, query the database with the code for the real data.

      I realize this is not Ionic, but I wrote this for a similar framework that does what you’re looking for:

      http://developer.telerik.com/featured/scanning-barcodes-nativescript-angular-2/

      Best,

      • Amit Karmakar

        Yes…. I was thinking the same!!! i said our backed developer to store that unique id and match that unique id from client place, then they will provide all real data.Thanks Nic…

        • Amit Karmakar

          Nic I want to learn Ionic 2, from where i should learn!! Any help!!

          • I no longer develop with Ionic Framework or Ionic 2 so I won’t be of much help with new content. I’ve since converted over to NativeScript which uses Angular 2.

            http://www.hybridtonative.com

            That site might help.

            Best,

      • Amod Kamat

        Nic, I am planning for new app development and planning to consider hybrid app. This app will include list views, QR code scanner and cloud web service interaction with local data storage. Please advise if hybrid app works for this and what would be better framework to start on? I am new to hybrid app dev and any advise will help. Thanks in advance

        • The more aggressive your application, the more you’ll need native or a native framework for performance reasons. I can’t make this decision for you, but you should keep your options open in case hybrid doesn’t work out for you.

          Best,

  • Anderson Trujillo

    for IOS no found.

  • Darren Cole

    This works great! Thanks! Two things though:
    1. On newer android, you may have to (as I did) go into Settings >> Apps >> “Your App Name” >> Permissions, then turn on camera for it to work.

    On my phone which uses Android 7.1.1, the image that you are trying to scan is upside down. This is difficult to use. Any way to correct this?

  • Pushkar Menaria

    ReferenceError: cordova is not defined
    at Object.scan (ng-cordova.min.js:7)
    at ChildScope.$scope.scanBarcode (app.js:30)
    at fn (eval at compile (ionic.bundle.js:27643), :4:224)
    at ionic.bundle.js:65429
    at ChildScope.$eval (ionic.bundle.js:30400)
    at ChildScope.$apply (ionic.bundle.js:30500)
    at HTMLButtonElement. (ionic.bundle.js:65428)
    at defaultHandlerWrapper (ionic.bundle.js:16792)
    at HTMLButtonElement.eventHandler (ionic.bundle.js:16780)
    at triggerMouseEvent (ionic.bundle.js:2953)

    • That error typically means you’re trying to test from a web browser or with a serving tool. You need to run native plugins on the device after building.

  • bekir

    I have a problem
    I apply my app this pluging and my app is crash after 4 times scan.

    • What do your logs say?

      • bekir

        i didnt see because i use ionic and i dont have a macbook also this plugin dont work on computer emilator but today i tried another iphone (5 se) it is close after 12 times scan so i think main problem is memory

        • With no logs I can’t help you, sorry

  • xenon

    Hello Nic, thank you for this tutorial, great job. I want to know if it’s possible to get the information inside the QRcode (like name, username, adress, …)?