Search code examples
eclipsecordovabarcode-scannercordova-plugins

Struggling to use Cordova barcodescanner plugin


I'm trying to create an application with Cordova (developing in eclipse, using JBoss Hybrid Mobile Tools + CordovaSim).

I have inspired the code snippet that's giving me problems on this example.

The error I get is:

!JavaScript ERROR: TypeError: 'undefined' is not an object (evaluating 'cordova.plugins.barcodeScanner') on line 6 for http://localhost:54726/js/QRScan.js 

QRScan.js only contains the following code (so basically as in the example):

var scanBut = document.getElementById('QRScanButton');
scanBut.onclick = quickScan();


function quickScan(){
    cordova.plugins.barcodeScanner.scan(
            function (result) {
                var s = "Result: " + result.text + "<br/>" +
                "Format: " + result.format + "<br/>" +
                "Cancelled: " + result.cancelled;
                resultDiv.innerHTML = s;
            }, 
            function (error) {
                alert("Scanning failed: " + error);
            }
        );
}

And I made sure my index.html contains the following line at the appropriate spot:

<script type="text/javascript" src="cordova.js"></script>

Finally my xml file should be configured correctly, I imported the correct plugin, the file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0"
    id="csam.test" version="1.0.0">
    <name>csam test</name>

    <description>
        A sample Apache Cordova application that responds to the
        deviceready
        event.
    </description>

    <author href="http://www.eclipse.org/thym" email="[email protected]">
        Eclipse.org -
        Thym
    </author>

    <content src="index.html" />

    <access origin="*" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />

    <feature name="App">
        <param name="android-package" value="org.apache.cordova.App" />
    </feature>
    <feature name="BarcodeScanner">
        <param name="android-package" value="com.phonegap.plugins.barcodescanner.BarcodeScanner" />
        <param name="ios-package" value="CDVBarcodeScanner" />
        <param name="wp-package" value="BarcodeScanner" />
        <param name="id" value="cordova-plugin-barcodescanner" />
    </feature>



    <engine name="android" version="4.0.1" />
</widget>

Solution

  • Plugins must wait for the deviceready event for use. Here is the piece of code from the demo which waits for deviceready added back in.

    document.addEventListener("deviceready", init, false);
    function init() {
        document.querySelector("#startScan").addEventListener("touchend", startScan, false);
        var scanBut = document.getElementById('QRScanButton');
        scanBut.onclick = quickScan();
    }