Make camera work in Cordova apps

Recently I was working on a personal project of developing mobile app using Cordova. In that app, I used a QR code scanning plugin. Obviously that plugin need camera access to scan QR code. I followed the documentation of that plugin but the camera was not showing up. The common problem to make camera works with Cordova apps is the background of the web view must be transparent.

I am using onsen UI for creating the UI for my app and their templating system to create different pages in it. Here is the basic html file which comprises multiple views in the app, for example, identified by template id named index.html and scan.html. [code lang="html"] <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/onsenui.css"> <link rel="stylesheet" href="css/onsen-css-components.min.css"> <link rel="stylesheet" href="css/default.css"> <script src="js/onsenui.min.js"></script> </head> <body> <ons-navigator swipeable id="main-nav" page="index.html"></ons-navigator> <template id="index.html"> <ons-page id="index"> <ons-toolbar> <div class="center">Home</div> </ons-toolbar> <ons-card> <div class="content"> <div>Please click the button below to scan QR code</div> <div style="width: 100%"> <ons-button id="push-button-scan" class="center">Scan</ons-button> </div> </div> </ons-card> </ons-page> </template> <template id="scan.html"> <ons-page id="scan"> <ons-toolbar> <div class="left"><ons-back-button>Scan</ons-back-button></div> <div class="center">Scan</div> </ons-toolbar> <script src="js/scan.js"></script> </ons-page> </template> <script src="cordova.js"></script> <script src="js/navigation.js"></script> <script src="js/jquery.js"></script> </body> </html> [/code] The scan.html template is the view where we will use the camera which is used by the QR code scanning plugin. We just need to sure to make any opaque HTML elements transparent here to avoid covering the video. So when the scan.html view is loaded, we make it's background transparent dynamically by using the following javascript. [code lang="js"] window.document.querySelector('#scan').classList.add('transparent-body'); [/code] This is the css code which makes the `scan.html` background transparent as it loads. [css] .transparent-body { background: none transparent !important; opacity: 0 !important; } [/css] That's it. Camera works perfectly as expected.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top