Git Product home page Git Product logo

dynamsoft / barcode-reader-javascript Goto Github PK

View Code? Open in Web Editor NEW
169.0 14.0 111.0 134.6 MB

Dynamsoft Barcode Reader JavaScript SDK for package managers. PDF417, QR Code, DataMatrix, MaxiCode and more are supported.

Home Page: https://www.dynamsoft.com/barcode-reader/sdk-javascript/

License: Other

javascript-barcode javascript-qrcode barcode-reader web javascript npm-package barcode html5-barcode web-barcode pdf417 qrcode aztec-code webassembly sdk linear-barcode 1d-barcode

barcode-reader-javascript's Introduction

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

version downloads jsdelivr

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.

Basic Requirements

Understand the code

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

<!DOCTYPE html>
<html>
<body>
<div id="cameraViewContainer" 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/[email protected]/dist/dbr.bundle.js"></script>
<script>
  Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9");
  Dynamsoft.Core.CoreModule.loadWasm(["dbr"]);
  (async () => {
    let cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance();

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

    const resultsContainer = document.querySelector("#results");
    cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => {
      if (result.barcodeResultItems.length > 0) {
        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(["dbr"]): 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(view)

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

Note:

If you open the web page as file:/// or http:// , the camera may not work correctly because the MediaDevices: getUserMedia() method only works in secure contexts (HTTPS), in some or all supporting browsers.

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: How to 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

To utilize the SDK, the initial step involves including the corresponding resource files:

  • core.js encompasses common classes, interfaces, and enumerations shared across all Dynamsoft SDKs.
  • license.js introduces the LicenseManager class, which manages the licensing for all Dynamsoft SDKs.
  • utility.js encompasses auxiliary classes shared among all Dynamsoft SDKs.
  • dbr.js defines interfaces and enumerations tailored to the barcode reader module.
  • cvr.js introduces the CaptureVisionRouter class, which governs the entire image processing workflow.
  • dce.js comprises classes that offer camera support and basic user interface functionalities.

To simplify things, starting from version 10.0.21, we introduced dbr.bundle.js, which combines all six of the above files. In the following chapters, we will use dbr.bundle.js.

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/[email protected]/dist/dbr.bundle.js"></script>
  • UNPKG

    <script src="https://unpkg.com/[email protected]/dist/dbr.bundle.js"></script>
  • In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test.

    <script src="https://download2.dynamsoft.com/packages/[email protected]/dist/dbr.bundle.js"></script>

    However, please DO NOT use download2.dynamsoft.com resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself.

  • In frameworks like React and Vue, you may want to add the package as a dependency.

    npm i [email protected] -E
    # or
    yarn add [email protected] -E

    In frameworks you need to specify the engineResourcePaths.

Host the SDK yourself (optional)

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

  • From the website

    <script src="dynamsoft/distributables/[email protected]/dist/dbr.bundle.js"></script>
  • From node_modules

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

    Since @<version> are missing, you need to specify the engineResourcePaths.

Note:

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

    1. Upgrade your web application server to one that supports the application/wasm mimetype.
    2. Manually define the mimetype on your server. You can refer to the following resources for guidance:
      1. Apache
      2. IIS
      3. 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.

Prepare the SDK

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

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 customer portal.

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.

Specify the location of the "engine" files (optional)

This is usually only required with frameworks like Angular or React, etc. where the referenced JavaScript files such as cvr.js, dbr.js are 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 Dynamsoft.Core.CoreModule.engineResourcePaths:

//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files
Object.assign(Dynamsoft.Core.CoreModule.engineResourcePaths, {
  std: "https://cdn.jsdelivr.net/npm/[email protected]/dist/",
  dip: "https://cdn.jsdelivr.net/npm/[email protected]/dist/",
  core: "https://cdn.jsdelivr.net/npm/[email protected]/dist/",
  license: "https://cdn.jsdelivr.net/npm/[email protected]/dist/",
  cvr: "https://cdn.jsdelivr.net/npm/[email protected]/dist/",
  dbr: "https://cdn.jsdelivr.net/npm/[email protected]/dist/",
  dce: "https://cdn.jsdelivr.net/npm/[email protected]/dist/"
});

Set up and start image processing

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
await Dynamsoft.Core.CoreModule.loadWasm(["dbr"]);

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; // 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);
    }
});

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 view, which is then passed to cameraEnhancer, and its content is displayed on the webpage.

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

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. In our particular case, our focus is on identifying barcodes within the images, so it's sufficient to define the callback function onDecodedBarcodesReceived:

const resultsContainer = document.querySelector("#results");
const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver();
resultReceiver.onDecodedBarcodesReceived = (result) => {
  if (result.barcodeResultItems.length > 0) {
    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`;
    }
  }
};
cvRouter.addResultReceiver(resultReceiver);

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

const resultsContainer = document.querySelector("#results");
cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => {
  if (result.barcodeResultItems.length > 0) {
    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`;
    }
  }
}});

Check out CapturedResultReceiver for more information.

Start the process

With the setup now complete, we can proceed to process the images in two straightforward steps:

  1. Initiate the image source to commence image acquisition. In our scenario, we invoke the open() method on cameraEnhancer to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to cvRouter as per its request.
  2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode.
await cameraEnhancer.open();
await cvRouter.startCapturing("ReadSingleBarcode");

Note:

  • cvRouter is engineered to consistently request images from the image source.
  • Various preset templates are at your disposal for barcode reading:
Template Name Function Description
ReadBarcodes_Default Scans a single barcode.
ReadSingleBarcode Quickly scans a single barcode.
ReadBarcodes_SpeedFirst Prioritizes speed in scanning multiple barcodes.
ReadBarcodes_ReadRateFirst Maximizes the number of barcodes read.
ReadBarcodes_Balance Balances speed and quantity in reading multiple barcodes.
ReadDenseBarcodes Specialized in reading barcodes with high information density.
ReadDistantBarcodes Capable of reading barcodes from extended distances.

Read more on the preset CaptureVisionTemplates.

Customize the process

Adjust the preset template settings

When making adjustments to some basic tasks, we often only need to modify SimplifiedCaptureVisionSettings.

Change barcode settings

The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code.

let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode");
settings.barcodeSettings.barcodeFormatIds =
  Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE;
await cvRouter.updateSettings("ReadSingleBarcode", settings);
await cvRouter.startCapturing("ReadSingleBarcode");

For a list of adjustable barcode settings, check out SimplifiedBarcodeReaderSettings.

Retrieve the original image

Additionally, we have the option to modify the template to retrieve the original image containing the barcode.

let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode");
settings.capturedResultItemTypes |= 
  Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE;
await cvRouter.updateSettings("ReadSingleBarcode", settings);
await cvRouter.startCapturing("ReadSingleBarcode");

Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time.

let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode");
settings.capturedResultItemTypes = 
  Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE |
  Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE;
await cvRouter.updateSettings("ReadSingleBarcode", settings);
await cvRouter.startCapturing("ReadSingleBarcode");

Please be aware that it is necessary to update the CapturedResultReceiver object to obtain the original image. For instance:

const EnumCRIT = Dynamsoft.Core.EnumCapturedResultItemType;
resultReceiver.onCapturedResultReceived = (result) => {
  let barcodes = result.items.filter(item => item.type === EnumCRIT.CRIT_BARCODE);
  if (barcodes.length > 0) {
    let image = result.items.filter(
      item => item.type === EnumCRIT.CRIT_ORIGINAL_IMAGE
    )[0].imageData;
    // The image that we found the barcode(s) on.
  }
};
Change reading frequency to save power

The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds:

Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion.

let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode");
settings.minImageCaptureInterval = 500;
await cvRouter.updateSettings("ReadSingleBarcode", settings);
await cvRouter.startCapturing("ReadSingleBarcode");
Specify a scan region

You can use the parameter roi (region of interest) together with the parameter roiMeasuredInPercentage to configure the SDK to only read a specific region on the image frames. For example, the following code limits the reading in the center 25%( = 50% * 50%) of the image frames:

let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode");
settings.roiMeasuredInPercentage = true;
settings.roi.points = [
  { x: 25, y: 25 },
  { x: 75, y: 25 },
  { x: 75, y: 75 },
  { x: 25, y: 75 },
];
await cvRouter.updateSettings("ReadSingleBarcode", settings);
await cvRouter.startCapturing("ReadSingleBarcode");

While the code above accomplishes the task, a more effective approach is to restrict the scan region directly at the image source, as demonstrated in the following code snippet.

  • With the region configured at the image source, the images are cropped right before they are gathered for processing, eliminating the necessity to modify the processing settings further.
  • cameraEnhancer elevates interactivity by overlaying a mask on the video, providing a clear delineation of the scanning region.
  • See also: CameraEnhancer::setScanRegion
cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(view);
cameraEnhancer.setScanRegion({
  x: 25,
  y: 25,
  width: 50,
  height: 50,
  isMeasuredInPercentage: true,
});

Edit the preset templates directly

The preset templates have a lot more settings that can be customized to best suit your use case. If you download the SDK from Dynamsoft website, you can find the templates under

  • "/dynamsoft-barcode-reader-js-10.2.10/dynamsoft/resources/barcode-reader/templates/"

Upon completing the template editing, you can invoke the initSettings method and provide it with the template path as an argument.

await cvRouter.initSettings("PATH-TO-THE-FILE"); //e.g. "https://your-website/ReadSingleBarcode.json")
await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the json file.

Filter the results (Important)

While processing video frames, it's common for the same barcode to be detected multiple times. To enhance the user experience, we can use MultiFrameResultCrossFilter object, having two options currently at our disposal:

Option 1: Verify results across multiple frames
let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter();
filter.enableResultCrossVerification("barcode", true);
await cvRouter.addResultFilter(filter);

Note:

  • enableResultCrossVerification was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes.
Option 2: Eliminate redundant results detected within a short time frame
let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter();
filter.enableResultDeduplication("barcode", true);
await cvRouter.addResultFilter(filter);

Note:

  • enableResultDeduplication was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time.

Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored.

It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.2.10 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted.

Under certain circumstances, this duration can be extended with the method setDuplicateForgetTime().

let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter();
filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds.
await cvRouter.addResultFilter(filter);

You can also enable both options at the same time:

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

Add feedback

When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration".

The following code snippet adds a "beep" sound for when a barcode is found:

const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver();
resultReceiver.onDecodedBarcodesReceived = (result) => {
  if (result.barcodeResultItems.length > 0) {
    Dynamsoft.DCE.Feedback.beep();
  }
};
cvRouter.addResultReceiver(resultReceiver);

Customize the UI

The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to customize the UI.

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=10.2.10.

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 required for in-browser video streaming.

  • 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 Name Version
Chrome v78+1
Firefox v62+1
Edge v79+
Safari v14+

1 devices running iOS needs to be on iOS 14.3+ for camera video streaming to work in Chrome, Firefox or other Apps using webviews.

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/index.html.

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 about the APIs of the SDK

barcode-reader-javascript's People

Contributors

cube-j avatar dmgithubpublisher avatar keillion avatar shen-wb avatar tom-dynamsoft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

barcode-reader-javascript's Issues

License TL;DR?

Hey!

I followed the rabbit hole of the license statement in this repo down to the following PDF (which appears to be the relevant one, please correct me if I'm wrong). But it's a legal document and I'm an engineer, so it left me as clueless as I was before.

Can you please give me a TL;DR of your license that states what I can and can not do with this software? Like they do on https://www.tldrlegal.com/ and similar websites.

That would be great!

Thx!

update runtime settings to set region defination

For a particular reason i have to define the region defination as the code is defined in left most part of the image. tried the following code but the updateRuntimeSettings becomes null

scanner = scanner || await Dynamsoft.DBR.BarcodeScanner.createInstance();
let scanner_settings = await scanner.getRuntimeSettings();
console.log(scanner_settings);
scanner_settings.region.regionLeft=25;
await reader.updateRuntimeSettings(scanner_settings);

I tried the python sdk where i needed to set the runtime settings as follows

"RegionDefinition": {
      "BarcodeFormatIds": [
        "BF_ALL"
      ],
      "BarcodeFormatIds_2": [
        "BF2_POSTALCODE",
        "BF2_DOTCODE"
      ],
      "Bottom": 100,
      "ExpectedBarcodesCount": 0,
      "FormatSpecificationNameArray": null,
      "Left": 25,
      "MeasuredByPercentage": 1,
      "Name": "default",
      "Right": 32,
      "Top": 0
    },

Now i want the similar settings to be set on the js sdk

Error when importing on Electron

Hello, we are building a PoC for a client that has an application in Electron but we cannot import the module, I've tried different ways to import it but it's always the same error, could you help me?

The error is:

Uncaught TypeError: Cannot read property 'platform' of undefined

Image of the stacktrace:
image

Thanks in advance!

Stream fails to play inside iOS PWA application

We are having an issue where the video stream of the scanner implemented in a PWA on iOS Safari fails to load. It seems this has been a known issue.

A member of this bugreport forum mentions he's been in contact with your team to figure out this issue in the past. Do you know if this issue has been resolved in the latest iOS version? And if so, what are the nessesary steps we need to take to make sure this will be resolved?

Currently we're on version 9.2.13 of the SDK.

Cannot scan the PDF417 code in the driver license.

I am using the Dynamsoft barcode scanner in the Electron React.js project.

I've copied the react example in the examples folder and it's working with a bigger image but it's not scanning the PDF417 code in the driver license. Is there anyway to get it work?

Getting a segmentation fault in node

I'm getting this error when attempting to run code simple to the sample code for the node.js module.
/c/Program Files/nodejs/npm: line 44: 614 Segmentation fault "$NODE_EXE" "$NPM_CLI_JS" "$@"

Here's my code

async decode() {
    let reader;
    try {
      reader = await dbr.BarcodeReader.createInstance();
    } catch (err) {
      return err;
    }

    let results;
    try {
      results = await reader.decode('../test_id/id_back.jpg');
      for(let result of results){
        console.log(result.barcodeText);
      }
    } catch (err) {
      return err
    }

    reader.destroy();
}

async method BarcodeScanner.show throws an error if scanner was destroyed during it's execution

Hey, I'm using version 8.1.2 of https://www.npmjs.com/package/dynamsoft-javascript-barcode

Having a valid initialization and working scanner I've noticed the following (edge-case) error:
Let's say we have a SPA application, and a view/page that displays fullpage barcode scanner.
On view/page leave we call BarcodeScanner.destroy() method (for example in router guard in case of Vue framework) to destroy scanner and close video streams. An example of page leave would be simply using browser/device navigation back button.

If user redirects away from the page/view during barcode scanner initialization (speaking more precisely - during execution of BarcodeScanner.show() method) then the following error is thrown:

Uncaught (in promise) TypeError: Cannot set property 'srcObject' of null
    at h.eval (dbr.browser.mjs?6c78:11)`

and video stream is not closed correctly (a browser indicator that this page is using or camera/microphone is still being displayed).

Example code to reproduce this issue:

this.barcodeScannerInstance.show();
// this simulates cleanup on quick page leave - after 100ms just destroy scanner
setTimeout(() => {
  this.barcodeScannerInstance && this.barcodeScannerInstance.destroy();
}, 100);

BarcodeScanner.show() should perform an extra check for already destroyed scanner and correctly close video stream in such case.

throws "memory access out of bounds" under high load

Hi There,
Under some load (several concurrent calls from browser) I'm facing this wasm error message
"memory access out of bounds"

node:internal/event_target:777
process.nextTick(() => { throw err; });
^
RuntimeError: memory access out of bounds
at wasm://wasm/01172d22:wasm-function[11931]:0x401f33
at wasm://wasm/01172d22:wasm-function[152]:0x8d1ec
at wasm://wasm/01172d22:wasm-function[11901]:0x400804
at wasm://wasm/01172d22:wasm-function[341]:0xa9b73
at wasm://wasm/01172d22:wasm-function[340]:0xa9aa1
at wasm://wasm/01172d22:wasm-function[446]:0xad5d0
at wasm://wasm/01172d22:wasm-function[528]:0xb06f0
at wasm://wasm/01172d22:wasm-function[524]:0xb048a
at wasm://wasm/01172d22:wasm-function[510]:0xaf8ca
at wasm://wasm/01172d22:wasm-function[285]:0xa5803
Error: memory access out of bounds
at /usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:21490
at Function. (/usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:14143)
at Generator.next ()
at /usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:732
at new Promise ()
at d (/usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:477)
at Worker.u._dbrWorker.onmessage (/usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:13166)
at Worker.emit (node:events:390:28)
at Worker.emit (node:domain:475:12)
at MessagePort. (node:internal/worker:232:53)
{"eventType":"error","log":{}}
RuntimeError: memory access out of bounds
at wasm://wasm/01172d22:wasm-function[240]:0x90770
at wasm://wasm/01172d22:wasm-function[291]:0xa7c63
at BarcodeReaderWasm$decodeFileInMemory [as decodeFileInMemory] (eval at qd (/usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr-8.8.0.node.wasm.js:92:242), :9:10)
at /usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr-8.8.0.worker.js:108:48
at Generator.next ()
at b (/usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr-8.8.0.worker.js:21:73)
Error: memory access out of bounds
at /usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:21490
at Function. (/usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:14143)
at Generator.next ()
at /usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:732
at new Promise ()
at d (/usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:477)
at Worker.u._dbrWorker.onmessage (/usr/src/app/node_modules/dynamsoft-javascript-barcode/dist/dbr.pure.js:11:13166)
at Worker.emit (node:events:390:28)
at Worker.emit (node:domain:475:12)
at MessagePort. (node:internal/worker:232:53)
undefined

Node.js v17.1.0
Dynamsoft lib version 8.8.0
Docker base image:node:current-slim

Please cold you help me to solve it? Do I need to increase any wasm config setting maybe?
Thank you

MediaTrackCapabilities should have a torch field in it's interface?

I had a piece of code that checks for the availability of the torch in the mobile device i'm using:
const capabilities = await cameraEnhancer.getCapabilities();

But by doing this I get a typescript error:
Property 'torch' does not exist on type 'MediaTrackCapabilities'.

By checking the lib.dom.d.ts I can actually see that said iterface (MediaTrackCapabilities) does not have a torch declaration:

interface MediaTrackCapabilities {
    aspectRatio?: DoubleRange;
    autoGainControl?: boolean[];
    channelCount?: ULongRange;
    deviceId?: string;
    displaySurface?: string;
    echoCancellation?: boolean[];
    facingMode?: string[];
    frameRate?: DoubleRange;
    groupId?: string;
    height?: ULongRange;
    noiseSuppression?: boolean[];
    sampleRate?: ULongRange;
    sampleSize?: ULongRange;
    width?: ULongRange;
}

Is the interface missing the "torch" specific or have I done something wrong in my code?

Node.js: The browser doesn't support Webassembly.

I have tried to install the dynamsoft-javascript-barcode package using npm and execute the example code provided here. It was throwing me the following error saying Webassembly is not supported in the browser(As node doesn't naively support webassembly). I've also found this instruction to wrap the sdk for linux environment. But, I was wondering if there is a way where would could use the bar-code reader right of the bat skipping the manual build procedure.

Error:

Error: 'Constructor BarcodeReader(productKeys)': The browser doesn't support Webassembly.
    at Error (native)
    at then.a._loadWasmStatus (\path\to\project\dbr\dbr.min.js:63:430)
    at \path\to\project\dbr\dbr.min.js:63:101
    at Timeout._onTimeout (\path\to\project\dbr\dbr.min.js:15:423)
    at tryOnTimeout (timers.js:224:11)
    at Timer.listOnTimeout (timers.js:198:5)

Auto Zoom broken after iOS 17

I noticed this error in my own application, but it can be observed on Dynamsoft's own demo, seemingly after iOS 17.
https://demo.dynamsoft.com/barcode-reader-js/common-oned/

After a few scans with auto zoom enabled, the following error occurs:

Failed to load resource: FetchEvent.respondWith received an error: TypeError: Load failedUnhandled Promise Rejection: TypeError: The provided value is non-finite

From that point, no other scans will work until the page is refreshed.

Content Security Policy violations due to needing unsafe-eval for dbr-8.6.3.wasm.js

I am using dynamsoft-barcode-reader @8.6.3 in a web application built with React. We recently had a security audit of the application that recommended adding a stricter Content Security Policy. Due to the use of the eval function in the wasm.js file, we are unable to remove unsafe-eval from our content security policy, which the audit recommends.

Do you have a way to avoid using the wasm.js script altogether, or do you have future plans to remove the use of eval in these JavaScript files?

Here is the line where the import failure occurs when unsafe-eval is not part of the Content Security Policy:
image

https://github.com/Dynamsoft/javascript-barcode/blob/3f4fc90c722d324b4aa453c13d7e60bb12a25eed/dist/dbr-8.6.3.worker.js#L25

3 uses of eval in dbr-8.6.3.wasm.js:
https://github.com/Dynamsoft/javascript-barcode/blob/3f4fc90c722d324b4aa453c13d7e60bb12a25eed/dist/dbr-8.6.3.wasm.js#L78
https://github.com/Dynamsoft/javascript-barcode/blob/3f4fc90c722d324b4aa453c13d7e60bb12a25eed/dist/dbr-8.6.3.wasm.js#L120

jsDelivr CDN SSL certificate error

I am currently utilizing the Dynamsoft JavaScript Barcode library in my project, specifically version 9.6.20 hosted via the jsDelivr CDN. Today, I encountered an SSL certificate error when trying to access the library at the following URL:
https://cdn.jsdelivr.net/npm/[email protected]/dist/dbr-9.6.20.browser.worker.js

The specific error displayed in my browser is NET::ERR_CERT_COMMON_NAME_INVALID. This error is preventing the library from loading properly, which is impacting the functionality of my application.

Do you recommend any specific steps to circumvent or fix this issue temporarily while a permanent solution is being worked on?
Is there an alternative CDN or method of accessing the library that you could recommend during this disruption?

404 not found for dbr-8.6.3.worker

I have installed:

"dynamsoft-javascript-barcode": "^8.6.3",

My code references:

DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/[email protected]/dist/";

When I attempt to use it:

image

Why is it referencing a different URL? I had this all working under 8.6.1

Demo

could someone create a demo page so I can pull it up on my phone and verify it actually works without having to install everything first?

8.8.3 references dbr-8.8.0.node.wasm file

Hi There,

v8.8.0 works like charm here, but I'm struggling to use 8.8.3 in node.js. Runtime this error appears:
RuntimeError: abort(Error: ENOENT: no such file or directory, open 'c:\Users\xy\source\repos\testool\node_modules\dynamsoft-javascript-barcode\dist\dbr-8.8.0.node.wasm') at Error
dist folder contains 8.8.3 files correctly.

I found that dbr-8.8.3.node.wasm.js contains reference to 8.8.0.node.wasm:
"var H;H="dbr-8.8.0.node.wasm";if(!kb())"
Is it intentional?

Please, could you check and help to find out the solution?
(npm install/uninstall, node_modules folder cleanup etc. has already been performed)
Thank you

QR codes recognition failures

These 3 artistic QR codes failed to be recognized, at least i wasn't able to do it.
That's said your SDK isn't targeting these use cases just yet but QR codes are spreading in our everyday life more and more.

each-body-has-its-art
baudrillard
toast

Feel free to close this issue if it doesn't meet your roadmap.

WebpackError: Cannot set property 'engineResourcePath' of undefined

I have followed your webpack example and I'm trying to implement this example into a Gatsby app.
During development, when running in the browser, everything is running fine with the config below:

services/dbr.js

/* eslint-disable no-console */
import { BarcodeReader, BarcodeScanner } from "dynamsoft-javascript-barcode";

BarcodeReader.engineResourcePath = "/dbr/"; // Static folder path

// Please visit https://www.dynamsoft.com/customer/license/trialLicense to get a trial license
BarcodeReader.productKeys = process.env.GATSBY_DYNAMSOFT_TRIAL_KEY;

BarcodeScanner.bPlaySoundOnSuccessfulRead = true;

// DBR.BarcodeReader._bUseFullFeature = true; // Control of loading min wasm or full wasm.
export {
    BarcodeReader,
    BarcodeScanner
}

But when I try to build the app using npm run build = gatsby build, I get the following message:
WebpackError: TypeError: Cannot set property 'engineResourcePath' of undefined on line 4

Any idea what is going wrong here?

My versions:
node: v12.20.0
javascript-barcode: 8.0
gatsby: 2.28.1

[8.1] Barcode result text in trial version has appended exception string

Hi there,

I'm using the barcode scanner 8.1 version that was released yesterday.
Since we're still on the trial version (already have a contract for commercial version) an exception is added when a a barcode scan is succesful:

barcodeText: "[Attention(exceptionCode:-20010)] 9783161484100"

The last part is the barcode I need, the first part is some exception. Could this just be the clean output like it was in the previous version (8.0)?

I already see a different exception object that is stating that I'm on the trial version, so I don't know why this is needed.

Animated codes support suggestion

Hello there!

Your great SDK analyse each frame independently so it cannot handle such animated marketing appealing codes:

sequence-01

Such codes could be packaged in an animated GIF, AVIF or a video format.
My suggestion is to add an option to treat each frame as a part of the same code.

I apology for my weak english :-/

iOS 17.4.1 Error: Failed to play video. Timeout.

Hello,
Could you take a look on issue I'm facing with dynamsoft-barcode-reader

Full list of installed dependencies and versions:
"dynamsoft-barcode-reader": "10.0.21",
"dynamsoft-camera-enhancer": "4.0.1",
"dynamsoft-capture-vision-router": "2.0.32",
"dynamsoft-capture-vision-std": "1.0.0",
"dynamsoft-core": "3.0.33",
"dynamsoft-image-processing": "2.0.30",
"dynamsoft-license": "3.0.40",
"dynamsoft-utility": "1.0.21",

Case:
The integration was made fully according to the react-hook sample. Barcode scanner component is set up in modal window. For the first load of modal window with barcode scanner 'request for access to camera' message is shown -> scanning works as expected. But if i will close this modal window with scanner, lock phone for 1-2 minutes, unlock and try to open scanner one more time, 'request for access to camera' message is shown -> error appears, scanning not working.

Please take a look on the screenshots:
image
image

Thank you in advance

getting barcode image marked with detection results

I am trying to get results from image files using the Dynamsoft.DBR.BarcodeReader as follows

reader = reader || await Dynamsoft.DBR.BarcodeReader.createInstance();
let results = await reader.decode(this.files[0]);
let res_img = await reader.getIntermediateResults();

I am getting the results of the bar code as text. But i also want the image that is marked with the bar code location. would i be able to get that using getIntermediateResults(); method ?

Any flash control?

Hi, implementing this into an webapp at the moment but theres a chance it might be used in low light conditions. Do you guys have any way built-in to enable the flashlight of a mobile device?

Cheers

Ionic Vue Unexpected token '<'

image

My code:

  import DBR from 'dynamsoft-javascript-barcode';

export default {
    name: 'TgDynamsoftTest',

    methods: {
      async scan() {
        DBR.BarcodeReader.productKeys = "hidden";

        let scanner = await DBR.BarcodeScanner.createInstance();
        await this.scanner.setUIElement(document.getElementById('scannerUI'));
        scanner.onFrameRead        = this.frameRead;
        scanner.onUnduplicatedRead = this.onUnduplicatedRead;
        await scanner.show();
        this.scanner = scanner;
      },

      frameRead(results) {
        console.log('frame read:', results);
      },

      onUnduplicatedRead(txt, result) {
        console.log('txt:', txt, ' result:', result);
      }
    }
  }

Known issue in iOS 17: Alert will stop video

While alert, video will stop in Safari of iOS17.x.

The video will not continue after you close the alert dialog.

The behavior can't be detected without invasive code, so we can't workaround it.

Solution:

Don't use alert in production.

Or offer a button of play which will call scanner.show() or scanner.open(), so end user can manually restart video.

Runtime error on createInstance

Hello,
I am using v8.1.2 of javascript-barcode scanner with react 16 and CRA 4.0.1, I am using example code but I have problem load scanner I still get this error, do you know where could be a problem?

Uncaught (in promise) TypeError: e is undefined
    _callee5$ dbr.browser.mjs:11
    tryCatch runtime.js:45
    invoke runtime.js:274
    method runtime.js:97
    a dbr.browser.mjs:11
    a dbr.browser.mjs:11
    onmessage dbr.browser.mjs:11
    _callee6$ dbr.browser.mjs:11
    tryCatch runtime.js:45
    invoke runtime.js:274
    method runtime.js:97
    s dbr.browser.mjs:11
    promise callback*d dbr.browser.mjs:11
    a dbr.browser.mjs:11
    a dbr.browser.mjs:11
    _callee7$/< dbr.browser.mjs:11
    _callee7$ dbr.browser.mjs:11
    tryCatch runtime.js:45
    invoke runtime.js:274
    method runtime.js:97
    a dbr.browser.mjs:11
    a dbr.browser.mjs:11
    loadWasm dbr.browser.mjs:11
    _callee8$ dbr.browser.mjs:11
    tryCatch runtime.js:45
    invoke runtime.js:274
    method runtime.js:97
    a dbr.browser.mjs:11
    a dbr.browser.mjs:11
    createInstanceInWorker dbr.browser.mjs:11
    _callee39$ dbr.browser.mjs:11
    tryCatch runtime.js:45
    invoke runtime.js:274
    method runtime.js:97
    u dbr.browser.mjs:11
    u dbr.browser.mjs:11
    createInstance dbr.browser.mjs:11
    _callee$ scanner.js:14
    tryCatch runtime.js:45
    invoke runtime.js:274
    method runtime.js:97
    asyncGeneratorStep Babel

error from broser:

Unhandled Rejection (TypeError): e is undefined
_callee$
src/components/dynamsoftScanner/scanner.js:12

   9 |     this.scanner = null;
  10 |     this.elRef = React.createRef();
  11 | }
> 12 | async componentDidMount(){
     | ^  13 |     try{
  14 |         this.scanner = this.scanner || await DBR.BarcodeScanner.createInstance();
  15 | 

tryCatch
node_modules/regenerator-runtime/runtime.js:45
invoke
node_modules/regenerator-runtime/runtime.js:274
./node_modules/regenerator-runtime/runtime.js/defineIteratorMethods/</prototype[method]
node_modules/regenerator-runtime/runtime.js:97
asyncGeneratorStep
node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:3
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.  Click the 'X' or hit ESC to dismiss this message

dbr.js:

import DBR from "dynamsoft-javascript-barcode";
require('dotenv').config();
//DBR.BarcodeReader.engineResourcePath = "/dynamsoft/dist/";
DBR.BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/[email protected]/dist/";
// Please visit https://www.dynamsoft.com/customer/license/trialLicense to get a trial license
DBR.BarcodeReader.productKeys = process.env.REACT_APP_DYNAMSOFT_SCANNER_KEY;
// DBR.BarcodeReader._bUseFullFeature = true; // Control of loading min wasm or full wasm.
export default DBR;

scanner react component:

import DBR from "./dbr";
import React from 'react';
import './BarcodeScanner.css';

class BarcodeScanner extends React.Component {
    constructor(props){
        super(props);
        this.bDestroyed = false;
        this.scanner = null;
        this.elRef = React.createRef();
    }
    async componentDidMount(){
        try{
            this.scanner = this.scanner || await DBR.BarcodeScanner.createInstance();

            if(this.bDestroyed){
                this.scanner.destroy();
                return;
            }

            this.scanner.setUIElement(this.elRef.current);
            this.scanner.onFrameRead = results => {
                if(results.length){
                    console.log(results);
                }
            };
            this.scanner.onUnduplicatedRead = (txt, result) => {
                //this.props.appendMessage(result.barcodeFormatString + ': ' + txt);
            };
            await this.scanner.open();

        }catch(ex){
            //this.props.appendMessage(ex.message);
            console.error(ex);
        }
    }
    componentWillUnmount(){
        this.bDestroyed = true;
        if(this.scanner){
            this.scanner.destroy();
        }
    }
    shouldComponentUpdate(){
        // Never update UI after mount, dbrjs sdk use native way to bind event, update will remove it.
        return false;
    }
    render() {
        return (
            <div ref={this.elRef} className="component-barcode-scanner">
                <svg className="dbrScanner-bg-loading" viewBox="0 0 1792 1792"><path d="M1760 896q0 176-68.5 336t-184 275.5-275.5 184-336 68.5-336-68.5-275.5-184-184-275.5-68.5-336q0-213 97-398.5t265-305.5 374-151v228q-221 45-366.5 221t-145.5 406q0 130 51 248.5t136.5 204 204 136.5 248.5 51 248.5-51 204-136.5 136.5-204 51-248.5q0-230-145.5-406t-366.5-221v-228q206 31 374 151t265 305.5 97 398.5z"></path></svg>
                <svg className="dbrScanner-bg-camera" style={{display:"none"}} viewBox="0 0 2048 1792"><path d="M1024 672q119 0 203.5 84.5t84.5 203.5-84.5 203.5-203.5 84.5-203.5-84.5-84.5-203.5 84.5-203.5 203.5-84.5zm704-416q106 0 181 75t75 181v896q0 106-75 181t-181 75h-1408q-106 0-181-75t-75-181v-896q0-106 75-181t181-75h224l51-136q19-49 69.5-84.5t103.5-35.5h512q53 0 103.5 35.5t69.5 84.5l51 136h224zm-704 1152q185 0 316.5-131.5t131.5-316.5-131.5-316.5-316.5-131.5-316.5 131.5-131.5 316.5 131.5 316.5 316.5 131.5z"></path></svg>
                <video className="dbrScanner-video" playsInline={true}></video>
                <canvas className="dbrScanner-cvs-drawarea"></canvas>
                <div className="dbrScanner-cvs-scanarea">
                    <div className="dbrScanner-scanlight" style={{display:"none"}}></div>
                </div>
                <select className="dbrScanner-sel-camera"></select>
                <select className="dbrScanner-sel-resolution"></select>
            </div>
        );
    }
}

export default BarcodeScanner;

Library fails with new relic

Hi, we wanted to start using new relic in our app. We have added the recommended scripts, but the website fails when trying to initialize barcode reader with the following error "license" is not allowed to change after "createInstance" or "loadWasm" is called.

This error happens before the first call to createInstance, so there was no misconfiguration on our side. The scanner worked well without new relic.

I have debugged it as far as I could, and I discovered that in the library code, the isEmpty check returns false, and this throws errors. Then I have removed those checks to validate if the license was really modified and this would fix the problem, but the real case seems to be the underlying logic in the isEmpty property. It checks if the variable task - a promise if I inferred it correct from minified code is not resolved and not empty, an that triggers the error, this may be a problem with instantiating the underlying scanner worker instance.

To reproduce this issue, please try creating worker instance with a basic new relic script added to html page. I cannot share our code as it includes new relic licenses but I can probably show a demo privately.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.