Reading barcode or QRcode using cordova or Phonegap

Posted on September 28, 2018 by Suresh Kamrushi in Android

Sharing code how you can easily install and configure “phonegap-plugin-barcodescanner” plugin for reading barcode and QRcode in hybrid mobile app. I am using cordova for development if you are using PhoneGap just replace “Cordova” with “phonegap” in commands below, rest will be same.

Step 1: Install plugin “phonegap-plugin-barcodescanner” using below command

cordova plugin add phonegap-plugin-barcodescanner

After running your will get “BUID SUCCESSFUL” message as below:
cordova_plugin_installation

Step 2: Add below code in your html. On click we are triggering scan() function which will launch camera and after reading data will be available in scan() function.

<input type='button' value='scann' onclick='scanApp.scan()' id='scanData'>

Step 3: Create file name “codescanner.js” and add below code:

var scanApp = {   
    // Application Constructor
    initialize: function () {
        this.bindEvents();
    },

    bindEvents: function () {
        document.addEventListener('deviceready', this.onDeviceReady);
    },

    onDeviceReady: function () {
        console.log('Received Device Ready Event');
        Log.initialize(app.displayLogLine);
    },
    scan: function () {
        cordova.plugins.barcodeScanner.scan(
                function (result) {
                    alert("Barcode/QR code data\n" + "Result: " + result.text + "\n" + "Format: " + result.format + "\n" + "Cancelled: " + result.cancelled);
                },
                function (error) {
                    alert("Scanning failed: " + error);
                }
        );
    },
};

Step 4: Include script file “codescanner.js” in your HTML file where you added button in step 2.
Step 5: Run below command to build it.

cordova run android

Now you can try reading any QR or barcode to get the data.
Hope it will help someone.

Tagged as ,