0% found this document useful (0 votes)
56 views9 pages

Barcode Scanning With Device Camera in SAPUI5 Applications (Without A Native Container) - SAP Blogs

Uploaded by

Sriram C S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views9 pages

Barcode Scanning With Device Camera in SAPUI5 Applications (Without A Native Container) - SAP Blogs

Uploaded by

Sriram C S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

Products
Products Industries
Industries Support
Support Training
Training Community
Community Developer
Developer Partner
Partner About
About  
Home / Community / Blogs + Actions

Barcode scanning with device camera in SAPUI5


applications (without a native container)
October 19, 2017 | 903 Views |

Ian MacGregor
more by this author

SAPUI5

JavaScript | barcode scanning | camera | Mobile

share
0 share
9 tweet share
29

Follow

https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 1/9
11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

The release of iOS 11 (on September 19, 2017) has bought some good news for anyone wanting to
incorporate barcode scanning into their SAPUI5 applications – support has been added to for the media
capture API. This means there is now the ability to access a device camera (and microphone) directly
from Safari (and all other major browsers except Opera mini – see http://caniuse.com/#feat=stream),
opening up the possibility to use barcode scanning in applications without the need for a native
container (i.e. Cordova).

In this blog I will demonstrate how a device camera can be accessed within a SAPUI5 application to
scan a barcode and populate the value of the barcode into an input field. This will be achieved in a plain
SAPUI5 web application which can be accessed via any device that has a camera and a supported
browser (we will implement a fallback solution when the application is accessed via a desktop or device
with no camera). We will make use of an external JavaScript library called QuaggaJS which will handle
the detection and decoding of barcodes.

What you will need

Some basic SAPUI5 knowledge


An IDE or text editor
The latest release of QuaggaJS library
Somewhere to publish your application
A mobile device with a camera

It is assumed that you already have (or know how to create) a UI5 project with a component, manifest,
view and controller…if not, then suggest you create one via WebIDE using the “SAPUI5 Application”
template.

Once you have your project, create a folder “libs” and add the QuaggaJS library (quagga.min.js) under
it.

https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 2/9
11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

Next, specify the resource in your manifest under sap.ui5 > resources > js (you could chose to load the
library using an alternate method if preferred)

"resources": {
"css": [
{
"uri": "css/style.css"
}
],
"js": [
{
"uri": "libs/quagga.min.js"
}
]
}

Add a property to the device model to track whether the device accessing our application has video
capability. To check this we use method MediaDevices.getUserMedia. Calling this method will prompt
the user to allow access to their camera (if the device has one)…note that it is possible to leave this

https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 3/9
11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

check to a later time (like when the user attempts to click the scan button which is the actual point the
application would like to access the camera), however we are doing it here so that the model property
can be used in our view to control the visibility of the scan button.

createDeviceModel: function() {
var oModel = new JSONModel(Device);
oModel.setDefaultBindingMode("OneWay");

// Disable the scan barcode button by default


oModel.setProperty("/barcodeScanEnabled",false);
if(navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
navigator.mediaDevices.getUserMedia({video:true}).then(function(stream){
// device supports video, which means will enable the scan button
oModel.setProperty("/barcodeScanEnabled",true);
}).catch(function(err){
// not supported, barcodeScanEnabled already default to false
});
}

return oModel;
}

Add the following controls to the view: a label, an input control to store the barcode value and a button to
trigger the scanning (visible if the device is capable).

<Label text="Barcode value" />


<Input id="scannedValue" placeholder="{= ${device>/barcodeScanEnabled} ? 'Use scan button to ent
<Button icon="sap-icon://bar-code" text="Scan" tooltip="Scan barcode" visible="{device>/barcodeS
<layoutData>
<l:GridData span="L2 M2" />
</layoutData>
</Button>

Add the two methods below to the controller. The first is the event handler for our scan button press
which will create and open a dialog – the content of the dialog is a single HTML div that is used to

https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 4/9
11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

display the video feed from the camera. We have attached a handler for the afterOpen event which will
call method _initQuagga (our second controller method) to initialise Quagga and then start the video
stream. For configuration options see https://serratus.github.io/quaggaJS/#configobject.

onScanForValue: function(oEvent){
if(!this._oScanDialog){
this._oScanDialog = new sap.m.Dialog({
title : "Scan barcode",
contentWidth : "640px",
contentHeight : "480px",
horizontalScrolling : false,
verticalScrolling : false,
stretchOnPhone : true,
content : [new sap.ui.core.HTML({
id : this.createId("scanContainer"),
content : "<div />"
})],
endButton : new sap.m.Button({
text : "Cancel",
press : function(oEvent){
this._oScanDialog.close();
}.bind(this)
}),
afterOpen : function(){
this._initQuagga(this.getView().byId("scanContainer").getDomRef()).done(function
// Initialisation done, start Quagga
Quagga.start();
}).fail(function(oError){
// Failed to initialise, show message and close dialog...this should not hap
// already checked for camera device ni /model/models.js and hidden the scan
MessageBox.error(oError.message.length ? oError.message : ("Failed to initia
onClose: function(){
this._oScanDialog.close();
}.bind(this)
});
}.bind(this));
}.bind(this),
afterClose : function(){
// Dialog closed, stop Quagga
Quagga.stop();
}
});
https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 5/9
11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

this.getView().addDependent(this._oScanDialog);
}

this._oScanDialog.open();
},

_initQuagga: function(oTarget){
var oDeferred = jQuery.Deferred();

// Initialise Quagga plugin - see https://serratus.github.io/quaggaJS/#configobject for deta


Quagga.init({
inputStream: {
type : "LiveStream",
target : oTarget,
constraints : {
width : {min: 640},
height : {min: 480},
facingMode : "environment"
}
},
locator: {
patchSize : "medium",
halfSample : true
},
numOfWorkers : 2,
frequency : 10,
decoder : {
readers : [{
format : "code_128_reader",
config : {}
}]
},
locate : true
}, function(error) {
if (error) {
oDeferred.reject(error);
} else {
oDeferred.resolve();
}
});

if(!this._oQuaggaEventHandlersAttached){
// Attach event handlers...

https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 6/9
11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

Quagga.onProcessed(function(result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;

if (result) {
// The following will attempt to draw boxes around detected barcodes
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), pa
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, {x: 0, y: 1}, drawingCtx, {color: "green
});
}

if (result.box) {
Quagga.ImageDebug.drawPath(result.box, {x: 0, y: 1}, drawingCtx, {color: "#0
}

if (result.codeResult && result.codeResult.code) {


Quagga.ImageDebug.drawPath(result.line, {x: 'x', y: 'y'}, drawingCtx, {color
}
}
}.bind(this));

Quagga.onDetected(function(result) {
// Barcode has been detected, value will be in result.codeResult.code. If requierd,
// on result.codeResult.code to ensure the correct format/type of barcode value has

// Set barcode value in input field


this.getView().byId("scannedValue").setValue(result.codeResult.code);

// Close dialog
this._oScanDialog.close();
}.bind(this));

// Set flag so that event handlers are only attached once...


this._oQuaggaEventHandlersAttached = true;
}

return oDeferred.promise();
}

https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 7/9
11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

Final step to be able to test your application is to publish it to a location that is accessible by the device
you are testing with – this could be a SAP gateway, SCP or any other web server.

A working example can be found here and the full code can be accessed here.

If you need a sample barcode to scan you can use this one or generate your own here.

Note that the code provided is configured to detect barcodes with symbology of Code 128, alternate
formats can be specified in the configuration object passed to Quagga.init.

Hopefully you have found parts of this blog useful…feel free to leave any feedback or questions below.

Alert Moderator

2 Comments
You must be Logged on to comment or reply to a post.

Mike Doyle

https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 8/9
11/20/2017 Barcode scanning with device camera in SAPUI5 applications (without a native container) | SAP Blogs

October 21, 2017 at 10:26 am

Nice blog Ian, thanks for sharing. Do you know if/when support for this arrived in Android?

Ian MacGregor Post author

October 22, 2017 at 4:42 am

Thanks Mike. It’s already supported in Android if using Android browser, Chrome, Opera (non mini version) or
Firefox…other less popular browsers seem to have some support but may require tweaking

Share & Follow Privacy Terms of Use Legal Disclosure Copyright Trademark Sitemap Newsletter

https://blogs.sap.com/2017/10/19/barcode-scanning-with-device-camera-in-sapui5-applications-without-a-native-container/ 9/9

You might also like