Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

dynamsoft-javascript-barcode

Package Overview
Dependencies
Maintainers
5
Versions
114
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dynamsoft-javascript-barcode

Dynamsoft Barcode Reader JS is a recognition SDK which enables you to embed barcode reading functionality in your web, desktop, and mobile applications. With a few lines of JavaScript code, you can develop a robust application to scan a linear barcode, QR

  • 9.6.2-beta-202301140102
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.5K
decreased by-82.41%
Maintainers
5
Weekly downloads
 
Created
Source

Barcode Reader for Your Website - User 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.

version downloads jsdelivr vulnerabilities

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.

Table of Contents

Popular Examples

You can also:

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.

Understand the code

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

<!DOCTYPE html>
<html>

<body>
    <script src="https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.2/dist/dbr.js"></script>
    <script>
        // Specifies a license, you can visit https://www.dynamsoft.com/customer/license/trialLicense?ver=9.6.2&utm_source=npm&product=dbr&package=js to get your own trial license good for 30 days. 
        Dynamsoft.DBR.BarcodeScanner.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9';
        // Initializes and uses the SDK
        (async () => {
            let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
            scanner.onFrameRead = results => {
                if (results.length > 0) console.log(results);
            };
            scanner.onUniqueRead = (txt, result) => {
                alert(txt);
            };
            await scanner.show();
        })();
    </script>
</body>

</html>

Code in Github   Run via JSFiddle   Run in Dynamsoft


About the code
  • The DBR-JS SDK is included in the code via the jsDelivr CDN.

In some rare cases, you might not be able to access the CDN. If this happens, you can use https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.0/dist/dbr.js for the test. However, please DO NOT use it in your production application because it is temporary. Instead, you can try hosting the SDK yourself.

  • license: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on Specify the license.

  • createInstance(): This method creates a BarcodeScanner object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface.

  • onFrameRead: This event is triggered every time the SDK finishes scanning a video frame. The results object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console.

  • onUniqueRead: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. txt holds the barcode text value while result is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode.

  • show(): This method brings up the built-in UI of the BarcodeScanner object and starts scanning.

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 pop up and the barcode location will be highlighted in the video feed.

Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser.

Note:

If you open the web page as file:/// or http:// , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera.

To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help.

  1. NGINX: Configuring HTTPS servers
  2. IIS: Create a Self Signed Certificate in IIS
  3. Tomcat: Setting Up SSL on Tomcat in 5 minutes
  4. Node.js: npm tls

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

Building your own page

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-javascript-barcode@9.6.2/dist/dbr.js"></script>
    
  • UNPKG

    <script src="https://unpkg.com/dynamsoft-javascript-barcode@9.6.2/dist/dbr.js"></script>
    
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.

Options to download the SDK:

Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this:

<script src="/dynamsoft-barcode-reader-js-9.6.2/dist/dbr.js"></script>

or

<script src="/node_modules/dynamsoft-javascript-barcode/dist/dbr.js"></script>

or

import { BarcodeScanner } from 'dynamsoft-javascript-barcode';

NOTE

  • Some older web application servers do not set .wasm mimetype as application/wasm. Upgrade your web application servers, or define the mimetype yourselves:

  • 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.

Configure the SDK

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

Specify the license

The SDK requires a license to work, use the API license to specify a license key.

Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY";

To test the SDK, you can request a 30-day trial license via the customer portal.

If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK.

Specify the location of the "engine" files

This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file.

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

//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files
Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.2/dist/";

Interact with the SDK

Create a BarcodeScanner object

You can use one of two classes ( BarcodeScanner and BarcodeReader ) to interact with the SDK. BarcodeReader is a low-level class that processes images directly. BarcodeScanner , on the other hand, inherits from BarcodeReader and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on BarcodeScanner in this guide.

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

Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY";
let scanner = null;
try {
    scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
} catch (ex) {
    console.error(ex);
}

Tip: When creating a BarcodeScanner 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 pScanner in the following code

Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY";
let pScanner = null;
document.getElementById('btn-scan').addEventListener('click', async () => {
    try {
        const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance());
    } catch (ex) {
        console.error(ex);
    }
});
Customize the BarcodeScanner Settings (optional)

Let's take a look at the following code snippets:

// Sets which camera and what resolution to use
let allCameras = await scanner.getAllCameras();
await scanner.setCurrentCamera(allCameras[0].deviceId);
await scanner.setResolution(1280, 720);
// Sets up the scanner behavior
let scanSettings = await scanner.getScanSettings();
// Disregards duplicated results found in a specified time period (in milliseconds).
scanSettings.duplicateForgetTime = 5000; // The default is 3000
// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time.
// (setting this value larger is a simple way to save battery power and reduce device heating).
scanSettings.intervalTime = 100; // The default is 0.
// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first.
// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed.
scanSettings.captureAndDecodeInParallel = false; // The default is true.
await scanner.updateScanSettings(scanSettings);
// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance"
await scanner.updateRuntimeSettings("speed");

// Makes changes to the template. The code below demonstrates how to specify enabled symbologies
let runtimeSettings = await scanner.getRuntimeSettings();
runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE;
await scanner.updateRuntimeSettings(runtimeSettings);

Try in JSFiddle

As you can see from the above code snippets, there are three types of configurations:

  • Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here.

  • get/updateScanSettings: Configures the behavior of the scanner which includes duplicateForgetTime and intervalTime, etc.

  • get/updateRuntimeSettings: Configures the decode engine with either a built-in template or a comprehensive RuntimeSettings object. For example, the following uses the built-in "speed" settings with updated localizationModes.

    await barcodeScanner.updateRuntimeSettings("speed");
    //await barcodeScanner.updateRuntimeSettings("balance"); //alternative
    //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative
    let settings = await barcodeScanner.getRuntimeSettings();
    settings.localizationModes = [
        Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS,
        Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY,
        Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0
    ];
    await barcodeScanner.updateRuntimeSettings(settings);
    

    Try in JSFiddle.

    See also settings samples.

Find the full list of the runtime settings here.

Customize the UI (optional)

The built-in UI of the BarcodeScanner object is defined in the file dist/dbr.ui.html . There are a few ways to customize it:

Modify the file dist/dbr.ui.html directly

This option is only possible when you Host the SDK yourself instead of using a public CDN.

Copy the file dist/dbr.ui.html to your application, modify it and use the the API defaultUIElementURL to set it as the default UI
// This line only takes effect before the method `createInstance()` is called.
Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE";
Append the default UI element to your page, customize it before showing it
<div id="div-ui-container"></div>
document.getElementById('div-ui-container').appendChild(scanner.getUIElement());
document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button
Build the UI element from scratch and connect it to the SDK with the API setUIElement(HTMLElement)
  1. Embed the video
<div id="div-ui-container" style="width:100%;height:100%;">
    <div class="dce-video-container" style="position:relative;width:100%;height:500px;"></div>
</div>
<script>
    (async () => {
        let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
        await scanner.setUIElement(document.getElementById('div-ui-container'));
        scanner.onFrameRead = results => {
            console.log(results);
        };
        scanner.onUniqueRead = (txt, result) => {
            alert(txt);
        };
        await scanner.show();
    })();
</script>

The video element will be created and appended to the DIV element with the class dce-video-container , make sure the class name is the same. Besides, the CSS property position of the DIV element must be either relative , absolute , fixed , or sticky .

Try in JSFiddle

  1. [Optional] Add the camera list and resolution list

If the class names of the created select elements match the default class names, i.e. dce-sel-camera and dce-sel-resolution respectively, the SDK will automatically populate the lists and handle the camera/resolution switching.

  <div id="div-ui-container" style="width:100%;height:100%;">
      <select class="dce-sel-camera"></select><br>
      <div class="dce-video-container" style="position:relative;width:100%;height:500px;"></div>
  </div>

Try in JSFiddle

<div id="div-ui-container">
    <select class="dce-sel-camera"></select>
    <select class="dce-sel-resolution"></select>
    <br>
    <div class="dce-video-container" style="position:relative;width:100%;height:500px;"></div>
</div>

Try in JSFiddle

By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them.

<select class="dce-sel-resolution">
    <option class="dce-opt-gotResolution" value="got"></option>
    <option data-width="1280" data-height="720">1280x720</option>
    <option data-width="1920" data-height="1080">1920x1080</option>
</select>

Try in JSFiddle

Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name dce-opt-gotResolution (as shown above) and the SDK will automatically use it to show the actual resolution.

See the section of the Explore Features guide on UI customization to learn more.

API Documentation

You can check out the detailed documentation about the APIs of the SDK at https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.2.

System Requirements

DBR requires the following features to work:

  • Secure context (HTTPS deployment)

    When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons

    • Access to the camera video stream is only granted in a security context. Most browsers impose this restriction.

    Some browsers like Chrome may grant the access for http://127.0.0.1 and http://localhost or even for pages opened directly from the local disk (file:///...). This can be helpful for temporary development and test.

    • Dynamsoft License requires a secure context to work.
  • WebAssembly, Blob, URL/createObjectURL, Web Workers

    The above four features are required for the SDK to work.

  • MediaDevices/getUserMedia

    This API is only required for in-browser video streaming. If a browser does not support this API, the Single Frame Mode will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera.

  • getSettings

    This API inspects the video input which is a MediaStreamTrack object about its constrainable properties.

The following table is a list of supported browsers based on the above requirements:

Browser NameVersion
Chromev59+1
Firefoxv52+ (v55+ on Android/iOS1)
Edge2v16+
Safari3v11+

1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews.

2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page.

3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+.

Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above.

How to Upgrade

If you want to upgrade the SDK from an old version to a newer one, please see how to upgrade.

Release Notes

Learn about what are included in each release at https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest.

Next Steps

Now that you have got the SDK integrated, you can choose to move forward in the following directions

  1. Check out the Official Samples and Demo
  2. Learn how to make use of the SDK features
  3. See how the SDK works in Popular Use Cases

Keywords

FAQs

Package last updated on 14 Jan 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc