How to Use Dynamsoft JavaScript Barcode SDK

If you always stay tuned to Dynamsoft Barcode SDK, you should have noticed that starting with version 5.1, the SDK includes a JavaScript library which is similar to Dynamic Web TWAIN. The article aims to help developers get familiar with the relevant JavaScript Barcode APIs and build web barcode reader apps quickly.

How does Dynamsoft JavaScript Barcode SDK Work

Dynamsoft JavaScript Barcode SDK is a part of Dynamsoft imaging and recognition modules. It does not run independently. See the following diagram:

Dynamsoft JavaScript imaging modules

 

The front-end library communicates with the back-end web service. One thing you have to know is that the service is cross-platform, though, only TWAIN JS module can work on Windows, Linux and macOS so far. The JavaScript Barcode SDK only works on Windows now.

Building Web Barcode Reader on Windows

Create an HTML page which contains an input field for loading image files, some check boxes for selecting barcode types, a button for reading barcodes, and a text area for displaying results.

Include dynamsoft.barcode.min.js:

<script type="text/javascript" src="http://www.dynamsoft.com/library/dbr/dynamsoft.barcode.min.js"></script>

Set a valid license:

dynamsoft.dbrEnv.productKey = "t0068NQAAAGesx+MAzzxDdPsKq7w2o/NatXjaIedwY/4h8b6dfEz+7OG8DZxgHoUfaHZC4xu+AoMxriB2L44DAKXJK25f0hg=";

Initialize the environment:

function onInitSuccess() {
    dbrObject = new dynamsoft.dbrEnv.BarcodeReader();
}

function onInitError(errCode, errMsg) {
    alert(errMsg);
}

dynamsoft.dbrEnv.init(onInitSuccess, onInitError);

Get checked types:

function getSelectedBarcodeTypes() {
    var vType = 0;
    var barcodeTypes = document.getElementsByName("BarcodeType");
    for (i = 0; i < barcodeTypes.length; i++) {
        if (barcodeTypes[i].checked == true)
            vType = vType | (barcodeTypes[i].value * 1);
    }

    return vType? vType : -1;
}

Scan barcodes:

function doReadBarcode() {
    dbrObject.barcodeFormats = getSelectedBarcodeTypes();
    var file = document.getElementById("fileToUpload").files[0];
    dbrObject.readBinaryAsync(file, "tmp.bmp", onBarcodeReadSuccess, onBarcodeReadFailure);
}

Display barcode results:

function onBarcodeReadSuccess(userData, result) {
    var count = result.getCount();
    var strMsg = "";
    if (count > 0) {
        for (var i = 0; i < count; i++) {
            strMsg += "<p>" + "Index: " + i + ". ";
            strMsg += "Barcode Type: " + result.get(i).formatString + ", ";
            strMsg += "Barcode Value: " + result.get(i).text + ".</p>";
        }
        document.getElementById('resultBox').innerHTML = strMsg;
    } else {
        alert("No barcode(s) found.");
    }
}

Open index.htm in Chrome:

JavaScript barcode reader

API Reference

http://www.dynamsoft.com/help/Barcode-Reader-JS/index.html

Source Code

https://github.com/dynamsoft-dbr/web