How to Build a Simple PWA Barcode QR Code Scanner

Progressive web apps (PWA), simply to say, are web apps that running like native apps on the desktop and mobile platforms. The advantages of PWA include installable, discoverable, linkable and so on. In this article, I’m trying to give a snapshot of a simple PWA barcode reader project built with Dynamsoft JavaScript barcode SDK.

What You Should Know About Dynamsoft JavaScript Barcode SDK

  • (Include JS libs, API docs and sample code)

Why PWA

Since from the day that mobile became the mainstream, users are spending more of time in native apps rather than on the web.

However, there are some drawbacks of using native apps:

  • It takes time to install native apps from the app store.
  • Users tend to install many apps but only use a few of them, which is a waste to system space.

Progressive web apps feature native app capabilities, such as push notification, offline work, background sync, sensor access and so on.

How doe a Progressive Web App Work

The main component of PWA is a service worker that runs in the background for caching web resources and providing native capabilities.

PWA diagram

PWA Browser Compatibility

Browser compatibility is important for web app development. You can find the PWA features supported by Chrome, Safari, Edge, Firefox and Opera here: https://www.goodbarber.com/blog/progressive-web-apps-feature-compatibility-based-on-the-browser-a883/.

Building and Publishing PWA Barcode QR Code Scanner

A standard progressive web app has to meet the following criteria:

  • Hosted over HTTPS.
  • Include a web manifest file.
  • Register a service worker.

We create a manifest file manifest.json as follows:

{
    "name": "BarcodeScanner",
    "short_name": "BarcodeScanner",
    "description": "A progressive web app for reading barcode and QR code.",
    "icons": [
        {
            "src": "icons/icon-192.png",
            "sizes": "192x192",
            "type": "image/png"
        }
    ],
    "start_url": "./index.html",
    "display": "standalone",
    "theme_color": "#2F3BA2",
    "background_color": "#3E4EB8"
}

With the manifest file, your app can be installed to the Android home screen and be launched as a native app.

Then we create a simple service-worker.js file:

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
});

self.addEventListener('fetch', function(e) {
  console.log('[ServiceWorker] Fetch', e.request.url);
});

The service worker needs to be registered in the main thread:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker
        .register('./service-worker.js')
        .then(function () {
            console.log('Service Worker Registered');
        });
}

So far, the main PWA feature has been done. The next step is to add the barcode recognition SDK to the application.

Here are the implementation steps:

  1. Initialize the barcode scanner object with a valid license key:

     var scanner = null;
     Dynamsoft.DBR.BarcodeReader.license = "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==";
     window.onload = async function () {
       try {
         await Dynamsoft.DBR.BarcodeScanner.loadWasm();
         await initBarcodeScanner();
       } catch (ex) {
         alert(ex.message);
         throw ex;
       }
     };
    
     async function initBarcodeScanner() {
       scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
     };
    
  2. Update the runtime settings:

     await scanner.updateRuntimeSettings("speed");
    
  3. Create an overlay to display the barcode scanning results:

     var overlay = null;
     var context = null;
    
     function initOverlay(ol) {
         overlay = ol;
         context = overlay.getContext('2d');
     }
    
     function updateOverlay(width, height) {
         if (overlay) {
             overlay.width = width;
             overlay.height = height;
             clearOverlay();
         }
     }
    
     function clearOverlay() {
         if (context) {
             context.clearRect(0, 0, overlay.width, overlay.height);
             context.strokeStyle = '#ff0000';
             context.lineWidth = 5;
         }
     }
    
     function drawOverlay(localization, text) {
         if (context) {
             context.beginPath();
             context.moveTo(localization.x1, localization.y1);
             context.lineTo(localization.x2, localization.y2);
             context.lineTo(localization.x3, localization.y3);
             context.lineTo(localization.x4, localization.y4);
             context.lineTo(localization.x1, localization.y1);
             context.stroke();
    
             context.font = '18px Verdana';
             context.fillStyle = '#ff0000';
             let x = [localization.x1, localization.x2, localization.x3, localization.x4];
             let y = [localization.y1, localization.y2, localization.y3, localization.y4];
             x.sort(function (a, b) {
                 return a - b;
             });
             y.sort(function (a, b) {
                 return b - a;
             });
             let left = x[0];
             let top = y[0];
    
             context.fillText(text, left, top + 50);
         }
     }
    
  4. Register the callback function for receiving and drawing the barcode detection results:

     scanner.onFrameRead = results => {
         clearOverlay();
    
         let txts = [];
         try {
           let localization;
           if (results.length > 0) {
             for (var i = 0; i < results.length; ++i) {
               txts.push(results[i].barcodeText);
               localization = results[i].localizationResult;
               drawOverlay(localization, results[i].barcodeText);
             }
             document.getElementById('result').innerHTML = txts.join(', ');
           }
           else {
             document.getElementById('result').innerHTML = "No barcode found";
           }
    
         } catch (e) {
           alert(e);
         }
       };
    

You can now test the PWA project with a web server. GitHub page is a nice choice for deploying and testing your PWA project.

Try my PWA barcode reader.

Desktop

PWA barcode reader desktop

Mobile

PWA add to home screen

Reference

About Dynamsoft Barcode Reader JavaScript Edition

Dynamsoft Barcode Reader JavaScript Edition is a JavaScript barcode scanning library based on the WebAssembly technology. It supports Code 39Code 93Code 128CodabarEAN-8EAN-13UPC-AUPC-EInterleaved 2 of 5 (ITF)Industrial 2 of 5 (Code 2 of 5 Industry, Standard 2 of 5, Code 2 of 5)ITF-14 QR codeDatamatrixPDF417 and Aztec code. The library is capable of scanning multiple barcodes from static images and camera video stream.

Source Code

https://github.com/yushulx/javascript-barcode-qr-code-scanner/tree/main/pwa