2
votes

I have been building small app with Intel XDK. I try to open Phonegap Barcode scanner but when launch button is clicked nothing happens. My goal is to scan a QR code and open inAppBrowser link containing result data. I have both Device (cordova-plugin-device) and Barcode Scanner (phonegap-plugin-barcodescanner) plugins installed with permissions for camera and flash.

Here is my code:

<script type="text/javascript">           

    document.addEventListener("deviceready", scanNow, false);

     function scanNow() {

cordova.plugins.barcodeScanner.scan(
  function (result) {
    //  alert("We got a barcode\n" +
     //      "Result: " + result.text + "\n" +
     //       "Format: " + result.format + "\n" +
     //       "Cancelled: " + result.cancelled);

         window.open("http://www.example.com?qr=" + result.text, '_system', 'location=no');


  }, 
  function (error) {
      alert("Error: " + error); 
  });}

</script> 

And this is the launch button:

<a role='button' onclick="scanNow();">Scan</a>

EDIT: I solved the problem by adding this link to a dummy script to my index page head.

<script src="cordova.js"></script>
1

1 Answers

1
votes

You don't need to call your scanNow() function on the deviceready event, you just need to insure that calls to it do not happen until after the deviceready event has fired. Since you're debugging, I would change that line to something like...

document.addEventListener("deviceready", alertDeviceReady, false);

...and add an alertDeviceReady() that gives you an alert or console message. Usually it takes a second or two, but can take longer on slow devices or if you've got some plugins that require a long init time.

This is going to be a security problem...

window.open("http://www.example.com?qr=" + result.text, '_system', 'location=no');

...because you should not open the webview to another page (you're navigating away from the built-in webview that your app is running inside of, you're not associated with a website).

You can use inAppBrowser to open an alternate view on top of the webview, but I advise that you use the explictly named inAppBrowser APIs and do not assume that it has been aliased to use window.open() -- because they have deprecated that usage and, I believe, it is not aliased in the default installation anymore. That is, try using...

cordova.inAppBrowser.open()

...instead.

See the docs here which will also include details regarding the current release for that plugin (which may only work with CLI 5+ builds) and contains a link to the github repo for more information.