Skip to content

Latest commit

 

History

145 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Barcode Reader for Your Website - Foundational API Guide

Dynamsoft Barcode Reader JavaScript Edition (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input.

In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website.

Hello World - Simplest Implementation

Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream.

Basic Requirements

  • Internet connection
  • A supported browser
  • Camera access

Please refer to system requirements for more details.

Understand the code

The complete code of the "Hello World" example is shown below

<!DOCTYPE html>
<html>
<body>
<div id="camera-view-container" style="width: 100%; height: 60vh"></div>
<textarea id="results" style="width: 100%; min-height: 10vh; font-size: 3vmin; overflow: auto" disabled></textarea>
<script src="https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader-bundle@11.6.5000/dist/dbr.bundle.js"></script>
<script>
  Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9");
  Dynamsoft.Core.CoreModule.loadWasm();
  (async () => {
    let cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance();

    let cameraView = await Dynamsoft.DCE.CameraView.createInstance();
    let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView);
    document.querySelector("#camera-view-container").append(cameraView.getUIElement());
    cvRouter.setInput(cameraEnhancer);

    const resultsContainer = document.querySelector("#results");
    await cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => {
      resultsContainer.textContent = '';
      for (let item of result.barcodeResultItems) {
        resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`;
      }
    }});

    let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter();
    filter.enableResultCrossVerification("barcode", true);
    filter.enableResultDeduplication("barcode", true);
    await cvRouter.addResultFilter(filter);

    await cameraEnhancer.open();
    await cvRouter.startCapturing("ReadSingleBarcode");
  })();
</script>
</body>
</html>

Code in Github   Run via JSFiddle   Run in Dynamsoft


About the code

  • Dynamsoft.License.LicenseManager.initLicense(): This method initializes the license for using the SDK in the application. Note that the string "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example points to an online license that requires a network connection to work. Read more on Specify the license.

  • Dynamsoft.Core.CoreModule.loadWasm(): This is an optional code. Used to load wasm resources in advance, reducing latency between video playing and barcode decoding.

  • Dynamsoft.CVR.CaptureVisionRouter.createInstance(): This method creates a CaptureVisionRouter object cvRouter which controls the entire process in three steps:

    • Retrieve Images from the Image Source
      • cvRouter connects to the image source through the ImageSourceAdapter interface with the method setInput().
        cvRouter.setInput(cameraEnhancer);

      The image source in our case is a CameraEnhancer object created with Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)

    • Coordinate Image-Processing Tasks
      • The coordination happens behind the scenes. cvRouter starts the process by specifying a preset template "ReadSingleBarcode" in the method startCapturing().
        cvRouter.startCapturing("ReadSingleBarcode");
    • Dispatch Results to Listening Objects
      • The processing results are returned through the CapturedResultReceiver interface. The CapturedResultReceiver object is registered to cvRouter via the method addResultReceiver(). For more information, please check out Register a result receiver.
        cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/});
      • Also note that reading from video is extremely fast and there could be many duplicate results. We can use a filter with result deduplication enabled to filter out the duplicate results. The object is registered to cvRouter via the method addResultFilter().
        cvRouter.addResultFilter(filter);

Read more on Capture Vision Router.

Run the example

You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor.

You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it.

When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed.

Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser.

Secure Contexts:

If you open the web page as http://, our SDK may not work correctly because the MediaDevices: getUserMedia() and other methods only work in secure contexts (HTTPS, localhost, 127.0.0.1, file://), in some or all supporting browsers.

Regarding configuring https on your server, these guides for nginx / IIS / tomcat / nodejs might help.

If the test doesn't go as expected, you can contact us.

Preparing the SDK

Step 1: Include the SDK

Use a public CDN

The simplest way to include the SDK is to use either the jsDelivr or UNPKG CDN. The "hello world" example above uses jsDelivr.

  • jsDelivr

    <script src="https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader-bundle@11.6.5000/dist/dbr.bundle.js"></script>
  • UNPKG

    <script src="https://unpkg.com/dynamsoft-barcode-reader-bundle@11.6.5000/dist/dbr.bundle.js"></script>
  • In frameworks like React, Vue and Angular, you may want to add the package as a dependency.

    npm i dynamsoft-barcode-reader-bundle@11.6.5000 -E
    # or
    yarn add dynamsoft-barcode-reader-bundle@11.6.5000 -E

    NOTE that in frameworks, you need to specify the location of the engine files.

Host the SDK yourself

Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application.

  • From the website

    Download Dynamsoft Barcode Reader JavaScript Package

    The resources are located at the path dynamsoft-barcode-reader-js-{version-number}/dist/.

  • From npm

    npm i dynamsoft-barcode-reader-bundle@11.6.5000 -E

    The resources are located at the path node_modules/<pkg>, without @<version>. You must copy "dynamsoft-xxx" packages elsewhere and add @<version>. The <version> can be obtained from package.json of each package. Another thing to do is to specify the engineResourcePaths so that the SDK can correctly locate the resources.

    Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting.

You can typically include SDK like this:

<script src="path/to/dynamsoft-barcode-reader-bundle@11.6.5000/dist/dbr.bundle.js"></script>

Note:

  • Certain legacy web application servers may lack support for the application/wasm MIME type for .wasm files. To address this, you have two options:

    1. Upgrade your web application server to one that supports the application/wasm MIME type.
    2. Manually define the MIME type on your server. You can refer to the guides for apache / IIS / nginx.
  • To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application.

    Cache-Control: max-age=31536000
    

    Reference: Cache-Control.

Step 2: Prepare the SDK

Before using the SDK, you need to configure a few things.

1. Specify the license

To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key.

Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9");

As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link.

Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples.

2. [Optional] Specify the location of the "engine" files

This step is optional and is only necessary if you need to specify a custom location for the engine files, such as when hosting these resources yourself or when your project's build setup does not automatically resolve them from the default location.

The purpose is to tell the SDK where to find the engine files (*.worker.js, *.wasm.js and *.wasm, etc.).

// In an ES Module
import { CoreModule } from "dynamsoft-barcode-reader-bundle";
CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/";
// Using the global namespace
Dynamsoft.Core.CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/";

This code uses the jsDelivr CDN as an example, feel free to change it to your own location.

Using the SDK

Step 1: Preload the module

The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries.

// Preload the .wasm files
Dynamsoft.Core.CoreModule.loadWasm();

Step 2: Create a CaptureVisionRouter object

To use the SDK, we first create a CaptureVisionRouter object.

Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9");

let cvRouter = null;
try {
    cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance();
} catch (ex) {
    console.error(ex);
}

Tip:

When creating a CaptureVisionRouter object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as pCvRouter in the following code:

Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9");

let pCvRouter = null; // The helper variable which is a promise of cvRouter
let cvRouter = null;

document.getElementById('btn-scan').addEventListener('click', async () => {
    try {
        cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance());
    } catch (ex) {
        console.error(ex);
    }
});

Step 3: Connect an image source

The CaptureVisionRouter object, denoted as cvRouter, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a CameraEnhancer object, identified as cameraEnhancer, which is specifically designed to capture image frames from the video feed and subsequently forward them to cvRouter.

To enable video streaming on the webpage, we create a CameraView object referred to as cameraView, which is then passed to cameraEnhancer, and its content is displayed on the webpage.

<div id="camera-view-container" style="width: 100%; height: 100vh"></div>
let cameraView = await Dynamsoft.DCE.CameraView.createInstance();
let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView);
document.querySelector("#camera-view-container").append(cameraView.getUIElement());
cvRouter.setInput(cameraEnhancer);

Step 4: Register a result receiver

Once the image processing is complete, the results are sent to all the registered CapturedResultReceiver objects. Each CapturedResultReceiver object may encompass one or multiple callback functions associated with various result types. This time we use onDecodedBarcodesReceived:

const resultsContainer = document.querySelector("#results");
const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver();
resultReceiver.onDecodedBarcodesReceived  = (result) => {
  resultsContainer.textContent = '';
  for (let item of result.barcodeResultItems) {
    // In this example, the barcode results are displayed on the page below the video.
    resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`;
  }
};
await cvRouter.addResultReceiver(resultReceiver);

You can also write code like this. It is the same.

const resultsContainer = document.querySelector("#results");
await cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => {
  resultsContainer.textContent